话不多说,直接上代码!
<?php class Sftp { // 初始配置为NULL private $config =NULL ; // 连接为NULL private $conn = NULL; // 是否使用秘钥登陆 private $use_pubkey_file= true; //sftp resource private $ressftp = NULL; // 初始化 public function init($config){ $this->config = $config ; } // 连接ssh ,连接有两种方式(1) 使用密码 // (2) 使用秘钥 public function connect(){ $methods['hostkey'] = $this->use_pubkey_file ? 'ssh-rsa' : [] ; $this->conn = ssh2_connect($this->config['host'], $this->config['port'], $methods); //(1) 使用秘钥的时候 if($this->use_pubkey_file){ // 用户认证协议 $rc = ssh2_auth_pubkey_file($this->conn,$this->config['user'],$this->config['pubkey_file'],$this->config['privkey_file'],$this->config['passphrase']); $this->ressftp = ssh2_sftp($this->conn); }else{ //(2) 使用登陆用户名字和登陆密码 $rc = ssh2_auth_password( $this->conn, $this->config['user'],$this->config['passwd']); $this->ressftp = ssh2_sftp($this->conn); } return $rc ; } // 文件上传 public function upftp( $local,$remote, $file_mode = 0777) { return copy($local,"ssh2.sftp://{$this->ressftp}".$remote); // return ssh2_scp_send($this->ressftp,$local,$remote,$file_mode); } //创建目录 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); } }
调用代码
$handle = new Sftp(); $handle->init($config); $handle->connect(); $re = $handle->ssh2_dir_exits($serverPath); //如果目录存在直接上传 if($re){ $handle->upftp("$localPath",$serverPath.$date); }else{ $handle->ssh2_sftp_mchkdir($serverPath); $handle->upftp("$localPath",$serverPath.$date); }