php通過sftp上傳文件

使用sftp需要安裝擴展!windows & centos7.6下安裝ssh2的php7.3擴展(不同對應版本)

sftp類

class Sftp {
    // 初始配置爲NULL
    private $config = NULL;
    // 連接爲NULL
    private $conn = NULL;
    //sftp resource
    private $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);
    }
    //創建目錄
    public function ssh2_sftp_mchkdir($path)  //使用創建目錄循環
    {
        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:本地和遠程路徑一定要準確!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章