如何通过 ssh 在 php 中获取远程文件并将文件直接返回到浏览器响应,而无需在网络服务器上创建文件副本 [英] 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

查看:43
本文介绍了如何通过 ssh 在 php 中获取远程文件并将文件直接返回到浏览器响应,而无需在网络服务器上创建文件副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am currently using a similar version of the below code to transfer a file from a remote server to my web server and then redirecting to the web server copy of the file in a publicly accessible web location.

$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 从亚马逊 s3 获取了一些文件.当我使用此方法时,api 将文件作为对象返回,因此我可以使用适当的标头将其直接发送到浏览器.像下面的例子.

I also get some files from amazon s3 using their api. When i use this method the api returns the file as an object so I am able to send it directly to the browser with the appropriate headers. like below example.

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

我的问题是如何从远程服务器流式传输/获取文件并将其以与底层版本相同的方式发送到浏览器,而无需在网络服务器上创建物理副本.非常感谢提前

My question is how can stream/get a file from a remote server and send it to the browser in the same way as the bottom version without creating a physical copy on the webserver. Many thanks in advance

推荐答案

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

You can use 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));
}

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

I have not tested the code, but it should work.

这篇关于如何通过 ssh 在 php 中获取远程文件并将文件直接返回到浏览器响应,而无需在网络服务器上创建文件副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆