2016-03-21 27 views
0

假設其可以查看在瀏覽器中的文件有一個使用標題顯示在頁面上的一個文件:下載,是由頭

header("Content-Length: " . filesize($file)); 
header("Content-type: application/pdf"); 
header("Content-disposition: inline"); 
header('Expires: 0'); 
header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 

我怎樣才能下載文件外,使用捲曲或的file_get_contents或以任何另一種方式?

我試過,但它下載一個空文件:

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_HEADER, true); 
curl_setopt($ch, CURLOPT_NOBODY, true); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
curl_setopt($ch, CURLOPT_URL, $url); //specify the url 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
$head = curl_exec($ch); 

header('Content-Disposition: attachment; filename="' . basename($url) . '"'); 
header("Content-Length: " . $url); 
header("Content-Type: application/octet-stream"); 

我嘗試使用的file_get_contents(),但是這可能是反正走錯了路。

任何人都可以幫忙嗎?

回答

0

此刻,您只能使用curl獲取標題,而不是實際的內容(body)本身。

當您更改到

curl_setopt($ch, CURLOPT_HEADER, false); 
curl_setopt($ch, CURLOPT_NOBODY, false); 

您將獲取二進制內容(內容處置:內聯應該沒問題)

如果您現在想爲其他先前獲取的文件下載用戶,只需打印出來即可。

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_HEADER, false); 
curl_setopt($ch, CURLOPT_NOBODY, false); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
curl_setopt($ch, CURLOPT_URL, $url); //specify the url 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
$body = curl_exec($ch); 

header('Content-Disposition: attachment; filename="EXAMPLE_FILE.txt"'); 
header("Content-Length: " . strlen($body)); 
header("Content-Type: application/octet-stream"); 

echo $body; 
+0

謝謝!雖然這是正確的,但我仍然沒有解決我的問題。我仍在下載一個空文件。 如果有人知道如何下載「Content-disposition:inline」文件,請幫忙! – Ivannnnn

+0

好的,所以如果你試圖在我的例子中用curl命令獲取它,$ body是空的?如果這樣的話,那麼源文件本身可能會有問題(是否可以直接通過瀏覽器獲取源文件?)。另外,你可以嘗試再次將CURLOPT_HEADER設置爲true,然後print_r響應(在我的例子中爲$ body)。也許我們看到更多信息。最後 - 檢查web服務器錯誤日誌,有時你會發現任何可能導致該問題的提示 –