以下是如何使用 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("无法连接到 $host 端口 $port.");
}
public function login($username, $password)
{
if (! @ssh2_auth_password($this->connection, $username, $password))
throw new Exception("无法使用用户名 $username " .
"和密码 $password 进行身份验证.");
$this->sftp = @ssh2_sftp($this->connection);
if (! $this->sftp)
throw new Exception("无法初始化 SFTP 子系统.");
}
public function uploadFile($local_file, $remote_file)
{
$sftp = $this->sftp;
$stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');
if (! $stream)
throw new Exception("无法打开文件: $remote_file");
$data_to_send = @file_get_contents($local_file);
if ($data_to_send === false)
throw new Exception("无法打开本地文件: $local_file.");
if (@fwrite($stream, $data_to_send) === false)
throw new Exception("无法从文件发送数据: $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";
}
?>