php5.6 sftp,PHP ssh链接sftp上传下载

*  构造函数.     */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');

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值