2014-10-27 80 views
1

假設我有與谷歌託管的圖片:https://www.google.ae/images/srpr/logo11w.png強制下載遠程託管圖片到瀏覽器

我想使這個映像文件下載,而不是開放的直接在瀏覽器中。

我曾嘗試:

<?php 
function downloadFile($file, $type) 
{ 
header("Cache-Control: public"); 
header("Content-Description: File Transfer"); 
header("Content-Disposition: attachment; filename=$file"); 
header("Content-Type: $type"); 
header("Content-Transfer-Encoding: binary"); 
header("Content-Length: ".filesize($file)); 
readfile($file); 
} 
downloadFile("img.jpg", "image/jpg"); 
?> 

這工作,但僅適用於本地託管imges,而不是圖像遠程託管像谷歌例如,上面。

+0

你無法控制另一個服務器如何處理請求。 – charlietfl 2014-10-27 13:52:41

+0

是的權利,但有沒有像使用JS或任何東西來實現這個機會? – user3800108 2014-10-27 13:53:43

+0

「不起作用」並不是什麼問題。打開PHP錯誤報告的高度,然後查看日誌。 – Quentin 2014-10-27 13:53:42

回答

3

readfile() manual page的第一個示例的標題爲 '強制使用的ReadFile()下載',具有.gif文件:

$file = 'monkey.gif'; 

if (file_exists($file)) { 
    header('Content-Description: File Transfer'); 
    header('Content-Type: application/octet-stream'); 
    header('Content-Disposition: attachment; filename='.basename($file)); 
    header('Expires: 0'); 
    header('Cache-Control: must-revalidate'); 
    header('Pragma: public'); 
    header('Content-Length: ' . filesize($file)); 
    readfile($file); 
    exit; 
} 

根據註釋部是如下提示:

如果fopen包裝已啓用,則可以使用此URL作爲文件名。有關如何指定文件名的更多詳細信息,請參閱fopen()。請參閱支持的協議和包裝以獲取有關各種包裝具有哪些功能的信息的鏈接,關於它們的用法的註釋以及它們可能提供的任何預定義變量的信息。

所以,如果你只是用$file = 'https://www.google.ae/images/srpr/logo11w.png';代替$file = 'monkey.gif';上面的腳本應該強制圖像下載。

當然,這種方法的一大缺點是圖像先傳輸到服務器,然後下載到客戶端。但是,由於@charlietfl wrote'你無法控制另一個服務器如何處理請求。'所以你不能直接鏈接到原始來源,並期望文件下載。