2012-09-01 28 views
0

我正在創建一個下載腳本,允許用戶下載可能位於本地服務器或遠程服務器上的文件。在這兩種情況下,我不要希望用戶找出原始文件的位置。直接將文件流式傳輸給用戶

在我的文件是我的服務器上的情況下,它很容易:

$data = file_get_contents('/local/path'); 
$name = 'myphoto'; 
force_download($name, $data); //codeigniter 

然而,對於遠程文件,如果我這樣做:

$data = file_get_contents('/remote/path'); 
$name = 'myphoto'; 
force_download($name, $data); 

它會下載到我的服務器第一,這將推遲用戶的下載。

有沒有一種方法可以通過我的服務器以某種方式將任何文件流式傳輸給用戶?所以它馬上開始下載?可能?

回答

4

看看fpassthru:它會比你擁有的多一點,但它應該做你想做的。

你會想是這樣的:

$fp = fopen('/remote/path'); 

    // you can't use force_download($name, $data): you'll need to set the headers 
appropriately by hand: see the code for the download_helper, but you'll need to set the mime type and content-length if you really care. 

    header('Content-Type: "'.$mime.'"'); 
         header('Content-Disposition: attachment;filename="myphoto"'); 
         header("Content-Transfer-Encoding: binary"); 
         header('Expires: 0'); 
         header('Pragma: no-cache'); 
         header("Content-Length: ".strlen($data)); 
    fpassthru($fp); 
+0

完美!我理解這裏的邏輯。 – Abs

相關問題