php 实现SFTP上传文件

php 实现sftp文件上传完全可以用php.net 官网中的方式,代码如下:

 

 1 class SFTPConnection
 2 {
 3     private $connection;
 4     private $sftp;
 5 
 6     public function __construct($host, $port=22)
 7     {
 8         $this->connection = @ssh2_connect($host, $port);
 9         if (! $this->connection)
10             throw new Exception("Could not connect to $host on port $port.");
11     }
12 
13     public function login($username, $password)
14     {
15         if (! @ssh2_auth_password($this->connection, $username, $password))
16             throw new Exception("Could not authenticate with username $username " .
17                                 "and password $password.");
18 
19         $this->sftp = @ssh2_sftp($this->connection);
20         if (! $this->sftp)
21             throw new Exception("Could not initialize SFTP subsystem.");
22     }
23 
24     public function uploadFile($local_file, $remote_file)
25     {
26         $sftp = $this->sftp;
27         $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');
28 
29         if (! $stream)
30             throw new Exception("Could not open file: $remote_file");
31 
32         $data_to_send = @file_get_contents($local_file);
33         if ($data_to_send === false)
34             throw new Exception("Could not open local file: $local_file.");
35 
36         if (@fwrite($stream, $data_to_send) === false)
37             throw new Exception("Could not send data from file: $local_file.");
38 
39         @fclose($stream);
40     }
41 }
42 
43 try
44 {
45     $sftp = new SFTPConnection("localhost", 22);
46     $sftp->login("username", "password");
47     $sftp->uploadFile("/tmp/to_be_sent", "/tmp/to_be_received");
48 }
49 catch (Exception $e)
50 {
51     echo $e->getMessage() . "\n";
52 }

但是在进行中遇到了一个问题, 我的php版本是 PHP 5.6.31 (cli) (built: Aug  2 2017 15:05:23)  , 在执行

$stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');

fopen的时候 执行文件 会报 "Segmentation fault" 的错误, 然后变成以下方式便可以解决

$stream = @fopen("ssh2.sftp://" . intval($sftp) . $remote_file, 'w');

其中,在实现sftp上传的时候,没有在意上传文件和上传目录的区别(例如: /upload 和 /upload/test.txt 的问题), 导致每次执行php 都会报 fopen(): Unable to open ssh2.sftp://5/upload on remote host. 问题解决方法就是 认真, 大写的认真

以上就是php做的, 只要登录sftp服务器 进行查看便知道结果.

sftp 命令登录方式:

sftp -oPort=port  user@server 然后输入密码, 进去之后可以到相对的目录查看文件是否存在.

 

posted @ 2018-03-21 18:14  lxiaodong  阅读(5763)  评论(0编辑  收藏  举报