|
ssh2_sftp
Initialize SFTP subsystem
(PECL ssh2:0.10-0.9)
Example 2365. Opening a file via SFTP<?php Code Examples / Notes » ssh2_sftpdavid barnes
Here is an example of how to send a file with SFTP: <?php 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"; } ?> |
Change Languagessh2_auth_hostbased_file ssh2_auth_none ssh2_auth_password ssh2_auth_pubkey_file ssh2_connect ssh2_exec ssh2_fetch_stream ssh2_fingerprint ssh2_methods_negotiated ssh2_publickey_add ssh2_publickey_init ssh2_publickey_list ssh2_publickey_remove ssh2_scp_recv ssh2_scp_send ssh2_sftp_lstat ssh2_sftp_mkdir ssh2_sftp_readlink ssh2_sftp_realpath ssh2_sftp_rename ssh2_sftp_rmdir ssh2_sftp_stat ssh2_sftp_symlink ssh2_sftp_unlink ssh2_sftp ssh2_shell ssh2_tunnel |