如何通过 ssh 获取 php 中的远程文件并将文件直接返回到浏览器响应,而无需在 Web 服务器上创建文件的副本


How can I fetch a remote file in php over ssh and return file directly to the browser response without creating a copy of the file on the webserver

我目前正在使用以下代码的类似版本将文件从远程服务器传输到我的 Web 服务器,然后重定向到可公开访问的 Web 位置中文件的 Web 服务器副本。

$tempfile = "/mylocalfolder/tempfile.wav" 
if (file_exists($tempfile)) {
        unlink($tempfile);
    }
$selectedfile = htmlspecialchars($_GET["File"]);
$filelink = '/myremotefolder/'.$selectedfile;
$connection = ssh2_connect($remote_server_ip, 22);
ssh2_auth_password($connection, 'username', 'password');
//echo $filelink.','. $tempfile;
ssh2_scp_recv($connection, $filelink, "/mylocalfolder/tempfile.wav");
header( 'Location: /mylocalfolder/recording.wav' ) ;

我还使用他们的 API 从 amazon s3 获取一些文件。当我使用此方法时,api 将文件作为对象返回,因此我能够使用适当的标头将其直接发送到浏览器。就像下面的例子。

// Display the object in the browser
header("Content-Type: {$result['ContentType']}");
header("Content-Type: audio/wav");
echo $result['Body'];
}

我的问题是,如何在不创建物理副本的情况下,从远程服务器流式传输/获取文件并以与底部版本相同的方式将其发送到浏览器。 提前非常感谢

您可以使用

ssh2_sftp http://php.net/manual/en/function.ssh2-sftp.php...必须安装 SSH2 绑定作为 PECL 扩展 (http://php.net/manual/es/book.ssh2.php)

示例代码可能是...

$sftp = ssh2_sftp($connection);
$remote = fopen("ssh2.sftp://$sftp/path/to/file", 'rb');
header( 'Content-type: ......');
while(!feof($remote)){
    echo( fread($remote, 4096));
}

我还没有测试代码,但它应该可以工作。

你可以使用 phpseclib 下载文件:

require_once 'Net/SFTP.php';
$connection = new Net_SFTP($remote_server_ip);
if (!$connection->login('username', 'password')) die('Login Error');
// set some appropriate content headers
echo $connection->get($filelink);

或者你可以使用ssh2.sftp包装器 - 参见SilvioQ对这种方法的回答。