<?php
//需要开启 php_ssh2 扩展。安装扩展后 php.ini 里添加 extension=ssh2
class Sftp {
// 连接为NULL
private $conn = NULL;
// 是否使用秘钥登陆
private $usePubKey= false;
//sftp 句柄
private $sftp = NULL;
/**
* 构造函数.
*/
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 = 0777
return 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');