最近客户传输数据需要支持sftp传输,调了好久,做一次记录:
需要ssh2扩展支持:
编译安装扩展:
下载地址
wget http://www.libssh2.org/download/libssh2-1.4.2.tar.gz
wget http://pecl.PHP.net/get/ssh2-0.12.tgz
安装libssh步骤
tar -zxvf libssh2-1.4.2.tar.gz
cd libssh2-1.4.2
./configure --prefix=/usr/local/libssh2
make
make test
make install
安装ssh2步骤
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
找到php.ini文件,打开后加入:
extension=ssh2.so
直接上实现代码示例:
<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);
$sftpStream= fopen('ssh2.sftp://' . intval($sftp) . '/path/to/file', 'r');
try {
if (!$sftpStream) {
throw new Exception("Could not open remote file: 远端文件错误");
}
$data_to_send = @file_get_contents(“本地文件路径”);
if ($data_to_send === false) {
throw new Exception("Could not open local file: 本地文件打开错误");
}
if (@fwrite($sftpStream, $data_to_send) === false) {
throw new Exception("Could not send data from file: 写入错误");
}else{
$result = true;
}
fclose($sftpStream);
} catch (Exception $e) {
error_log('Exception: ' . $e->getMessage());
fclose($sftpStream);
}
?>
注意:
1、本地文件路径和名称必须要存在
2、远端文件自动创建
参考官方文档:
http://php.net/manual-lookup.php?pattern=SFTP&scope=quickref
http://php.net/manual/en/book.ftp.php
|