2013-04-22 199 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將輸出(文件)直接發送到瀏覽器。

相關問題