* 构造函数. */public function __construct(){
$sftp_config = array("host" => "", // SFTP服务器ip地址"username" => "", // SFTP服务器用户名"password" => "", // SFTP服务器密码(有密码就不用提供公钥,秘钥)"port" => "22", // SFTP服务器端口号"pubkeyfile" => "id_rsa_logo.pub", // SFTP服务器秘钥文件"privkeyfile" => "id_rsa_logo", // SFTP服务器公钥文件"passphrase" => "" // 密码短语 );
$methods['hostkey'] = $this->usePubKey ? 'ssh-rsa' : [] ;
$this->conn = ssh2_connect($sftp_config['host'], $sftp_config['port'], $methods);if($this->usePubKey){ // 使用秘钥登录ssh2_auth_pubkey_file($this->conn, $sftp_config['username'], $sftp_config['pubkeyfile'], $sftp_config['privkeyfile'], $sftp_config['passphrase']);
$this->sftp = ssh2_sftp($this->conn);
}else{ // 使用用户名和密码登录ssh2_auth_password( $this->conn, $sftp_config['username'], $sftp_config['password']);
$this->sftp = ssh2_sftp($this->conn);
}
}// 下载文件public function download($remotFile = '/testdir/test.php', $localFile = '/data/sftp_file/test.php'){return copy("ssh2.sftp://{$this->sftp}" . $remotFile, $localFile); // 有可能报502错误,如报错则使用下面语句return copy("ssh2.sftp://" . intval($this->sftp) . $remotFile, $localFile);
}// 文件上传public function upload($remotFile = '/testdir/test.php', $localFile = '/data/sftp_file/test.php'){ //, $file_mode = 0777return copy($localFile, "ssh2.sftp://{$this->sftp}" . $remotFile); // 有可能报502错误,如报错则使用下面语句return copy($localFile, "ssh2.sftp://" . intval($this->sftp) . $remotFile);
}// 创建目录public function mkdir($remotPath = "/testdir/testdir2/testdir3/"){//可直接创建多级目录ssh2_sftp_mkdir($this->sftp, $remotPath, 0777, true);
}// 改变目录或文件权限public function chmod($remotPath = "/testdir/testdir2/testdir3/"){
ssh2_sftp_chmod ($this->sftp, $remotPath, 0755);
}// 判段目录或者文件是否存在public function exits($remotPath = "/testdir/testdir2/testdir3/"){return file_exists("ssh2.sftp://{$this->sftp}" . $remotPath); // 有可能报502错误,如报错则使用下面语句return file_exists("ssh2.sftp://" . intval($this->sftp) . $remotPath);
}
}
$this = new Sftp();
$remotPath = "/testdir/"; // 远程路径$localPath = __DIR__ . "/data/sftp_file/"; // 本地文件路径;//上传文件// 判断远程路径是否存在$exits = $this->exits($remotPath);// 如果目录不存在,创建目录if (!$exits) {
$this->mkdir($remotPath);
}//上传到sftp$this->upload($remotPath . 'test.txt', $localPath . 'test.txt');//下载文件//判断远程文件是否存在$exits = $this->exits($remotPath . 'test.txt');//如果不存在if (!$exits) {
echo "文件不存在无法下载";
die;
}
$this->download($remotPath.'test.txt', $localPath.'test.txt');