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

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 returns 文件作为 object,因此我可以使用适当的 headers 将其直接发送到浏览器。像下面的例子。

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

我的问题是如何从远程服务器 stream/get 以与底层版本相同的方式将文件发送到浏览器,而无需在网络服务器上创建物理副本。非常感谢

您可以使用 ssh2_sftp http://php.net/manual/en/function.ssh2-sftp.php ... you must install ssh2 bindings as PECL extension (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 对该方法的回答。