2013-04-22 115 views
3

我正在寻找允许用户直接从sftp服务器下载文件,但在浏览器中。如何使用PHP从SFTP服务器下载文件

我找到了读取文件和回显字符串(使用ssh2.sftp或phpseclib的连接)的方法,但我需要下载而不是读取。

此外,我见过的解决方案建议从sftp服务器下载到web服务器,然后使用web服务器的readfile()到用户的本地磁盘。但是这意味着两个文件传输,如果文件很大,我想这会很慢。

你能否直接从sftp下载到用户磁盘?

欢迎任何回应!

+0

PHP有[FTP功能](http://www.php.net/manual/en/ref.ftp.php) – DarkBee 2013-04-22 11:15:32

+2

* <以前的评论编辑> *没关系,我刚刚明白你的意思。你所需要做的就是使用'Content-Disposition:attachment'强制下载; filename =“yourfile.ext”标题,并按照您的要求回显数据。 – DaveRandom 2013-04-22 11:24:07

+0

干杯@DaveRandom - 这似乎工作! – coffeedoughnuts 2013-04-22 12:09:41

回答

4

如果你添加一个直接链接到你的html文件(即下载文本),你不需要任何php为了让用户直接从SFTP服务器下载。当然,如果你不想公开ftp服务器的证书,这将不起作用。

如果您希望通过服务器从SFTP获取文件,则必须先将文件下载到服务器,然后再将其发送回用户浏览器。

为此,有很多很多的解决方案。最小的开销很可能来自使用 phpseclib如下

<?php 
include('Net/SFTP.php'); 

$sftp = new Net_SFTP('www.domain.tld'); 
if (!$sftp->login('username', 'password')) { 
    exit('Login Failed'); 
} 

//adds the proper headers to tell browser to download rather than display 
header('Content-Type: application/octet-stream'); 
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"filename.remote\""); 

// outputs the contents of filename.remote to the screen 
echo $sftp->get('filename.remote'); 
?> 

不幸的是,如果该文件是不是由您的服务器/ PHP配置在内存中是允许更大,那么这也导致问题。

如果你想采取了一步,你可以尝试使用卷曲

//adds the proper headers to tell browser to download rather than display 
header('Content-Type: application/octet-stream'); 
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"filename.remote\""); 

$curl = curl_init(); 
curl_setopt($curl, CURLOPT_URL, "sftp://full_file_url.file"); #input 
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_SFTP); 
curl_setopt($curl, CURLOPT_USERPWD, "$_FTP[username]:$_FTP[password]"); 
curl_exec($curl); 
curl_close($curl); 

更多信息可以在PHP Manual Documentation找到。使用curl_exec()而不将CURLOPT_RETURNTRANSFER选项设置为true会导致curl将输出(文件)直接发送到浏览器。

相关问题