TP3.2存放类文件目录下(Common/Org/)新建php文件 sftp.class.php
php没有SFTP,使用的是SSH扩展
<?php
/********************************************
* MODULE:SFTP类
*******************************************/
class sftp{
// 初始配置为NULL
private $config =NULL ;
// 连接为NULL
private $conn = NULL;
// 是否使用秘钥登陆
private $use_pubkey_file= false;
// 初始化
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']);
//(2) 使用登陆用户名字和登陆密码
}else{
$rc = ssh2_auth_password( $this->conn, $this->config['user'],$this->config['passwd']);
}
return $rc ;
}
// 传输数据 传输层协议,获得数据
public function download($remote, $local){
return ssh2_scp_recv($this->conn, $remote, $local);
}
//传输数据 传输层协议,写入ftp服务器数据
public function upload($remote, $local,$file_mode=0664){
return ssh2_scp_send($this->conn, $local, $remote, $file_mode);
}
// 删除文件
public function remove($remote){
$sftp = ssh2_sftp($this->conn);
$rc = false;
if (is_dir("ssh2.sftp://{$sftp}/{$remote}")) {
$rc = false ;
// ssh 删除文件夹
$rc = ssh2_sftp_rmdir($sftp, $remote);
} else {
// 删除文件
$rc = ssh2_sftp_unlink($sftp, $remote);
}
return $rc;
}
}
?>
使用方法
import("Common/Org/sftp");
$config = array("host"=>"host","user"=>"","port"=>"","passwd"=>"");
$handle = new \sftp();
$handle->init($config);
$rc = $handle->connect();
//上传,成功返回true
dump($handle->upload("remotePath","localPath"));exit;
//下载,成功返回true
dump($handle->download("remotePath","localPath"));exit;
使用时要注意扩展和接收端服务器安装
PHP之SFTP扩展库编译安装注意事项
1、下载文件:
wget http://www.libssh2.org/download/libssh2-1.4.2.tar.gz
wget http://pecl.PHP.net/get/ssh2-0.12.tgz
2、安装 libssh2 在安装 SS2
tar -zxvf libssh2-1.4.2.tar.gz
cd libssh2-1.4.2
./configure --prefix=/usr/local/libssh2
make
make test
make install
3、SSH安装
tar -zxvf ssh2-0.12.tgz
cd ssh2-0.12
phpize(个人目录不同,例如:/usr/local/php/bin/phpize)
./configure --prefix=/usr/local/ssh2 --with-ssh2=/usr/local/libssh2 --with-php-config=/usr/local/php/bin/php-config //找到php-config路径
make
make test
make install
4、安装完成
安装完成后会在 /usr/local/php/lib/php/extensions目录下生成一些文件,可以不管
找到php.ini文件,打开后加入:
extension=ssh2.so