php通过sftp上传文件
生活随笔
收集整理的這篇文章主要介紹了
php通过sftp上传文件
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
使用sftp需要安裝擴展!windows & centos7.6下安裝ssh2的php7.3擴展(不同對應版本)
sftp類
class Sftp {// 初始配置為NULLprivate $config = NULL;// 連接為NULLprivate $conn = NULL;//sftp resourceprivate $ressftp = NULL;// 初始化public function __construct($config){$this->config = $config;$this->connect();}public function connect(){$this->conn = ssh2_connect($this->config['host'], $this->config['port']);if( ssh2_auth_password($this->conn, $this->config['username'], $this->config['password'])){$this->ressftp = ssh2_sftp($this->conn);}else{return "用戶名或密碼錯誤";}}// 下載文件public function downftp($remote, $local){return copy("ssh2.sftp://{$this->ressftp}".$remote, $local);}// 文件上傳public function upftp( $local,$remote, $file_mode = 0777){return copy($local,"ssh2.sftp://{$this->ressftp}".$remote);}//創(chuàng)建目錄public function ssh2_sftp_mchkdir($path) //使用創(chuàng)建目錄循環(huán){ssh2_sftp_mkdir($this->ressftp, $path,0777,true);}//判段目錄是否存在public function ssh2_dir_exits($dir){return file_exists("ssh2.sftp://{$this->ressftp}".$dir);} }上傳
public function SftpUpdate(){//本地文件目錄$localpath = "/test.txt"; //本地文件路徑$serverpath='/data/test'; //遠程目錄(需要上傳到的目錄)$config = array("host"=>"IP","username"=>"賬號","port"=>"22","password"=>"密碼");try {$sftp = new \App\Model\Sftp($config);$res = $sftp->ssh2_dir_exits("$serverpath");//如果目錄存在直接上傳if($res){$sftp->upftp($localpath,$serverpath);}else{$sftp->ssh2_sftp_mchkdir($serverpath);$sftp->upftp($localpath,$serverpath);}return 'ok';} catch (\Exception $e) {return $e->getMessage();} }Ps:本地和遠程路徑一定要準確!!!
總結(jié)
以上是生活随笔為你收集整理的php通过sftp上传文件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 支付宝支付-扫码支付详解
- 下一篇: 6.10心得