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 然后輸入密碼, 進去之后可以到相對的目錄查看文件是否存在.