2012-03-05 141 views
1

我試圖使用PHP CURL從Web服務器下載.exe文件到PC,使用CURL使Web服務器登錄自動進行。我遇到的問題是文件正在寫入瀏覽器窗口,而不是要求用戶保存或運行文件。我正在使用下面的代碼,我該如何解決這個問題,讓它像我想要的那樣工作?使用PHP CURL下載文件

$username = "myuser"; 
$password = "mypassword"; 
$url="http://www.mywebsite.com/files/softwaredownload/myfile.exe"; 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password"); 
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
curl_exec ($ch); 
curl_close($ch); 

回答

1

添加到您的這些代碼:

curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

...與$response = curl_exec($ch);取代curl_exec($ch),所以$響應的內容可能會被保存到與fwrite()file_put_contents()方法本地文件。

2

您應該設置標題,以便瀏覽器知道它必須顯示保存對話框。

Content-Disposition: attachment; filename=<file name.ext>

而且,要記住,Content-Type頭應該是Content-Disposition之前。

+0

謝謝您,添加Content-Disposition標頭完美運行。 – user988750 2012-03-07 16:55:00