php method to implement sftp upload: 1. Create the code "class SFTPConnection private $connection...try{...}catch{...}"; 2. Execute "sftp -oPort=port user @server" statement is enough.
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
How does php implement sftp upload?
php Implement SFTP file upload
php To implement SFTP file upload, you can completely use the method on the php.net official website. The code is as follows:
class SFTPConnection { private $connection; private $sftp; public function __construct($host, $port=22) { $this->connection = @ssh2_connect($host, $port); if (! $this->connection) throw new Exception("Could not connect to $host on port $port."); } public function login($username, $password) { if (! @ssh2_auth_password($this->connection, $username, $password)) throw new Exception("Could not authenticate with username $username " . "and password $password."); $this->sftp = @ssh2_sftp($this->connection); if (! $this->sftp) throw new Exception("Could not initialize SFTP subsystem."); } public function uploadFile($local_file, $remote_file) { $sftp = $this->sftp; $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w'); if (! $stream) throw new Exception("Could not open file: $remote_file"); $data_to_send = @file_get_contents($local_file); if ($data_to_send === false) throw new Exception("Could not open local file: $local_file."); if (@fwrite($stream, $data_to_send) === false) throw new Exception("Could not send data from file: $local_file."); @fclose($stream); } } try { $sftp = new SFTPConnection("localhost", 22); $sftp->login("username", "password"); $sftp->uploadFile("/tmp/to_be_sent", "/tmp/to_be_received"); } catch (Exception $e) { echo $e->getMessage() . "\n"; }
But I encountered a problem during the process. My php version is PHP 5.6.31 (cli) (built: Aug 2 2017 15:05:23). When executing
$stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');
fopen, execute the file A "Segmentation fault" error will be reported, and then it can be solved in the following way
$stream = @fopen("ssh2.sftp://" . intval($sftp) . $remote_file, 'w');
Among them, when implementing sftp upload, the difference between uploaded files and upload directories is not paid attention to (for example: /upload and /upload /test.txt), causing fopen(): Unable to open ssh2.sftp://5/upload on remote host to be reported every time php is executed. The solution to the problem is Serious, capitalized Serious
The above is done by php. Just log in to the sftp server to check and you will know the result.
sftp command login method:
sftp -oPort=port user@server and then enter the password , after entering, you can go to the relative directory to check whether the file exists.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to implement sftp upload in php. For more information, please follow other related articles on the PHP Chinese website!