使用PHP CURL下载文件

时间:2012-03-05 21:45:56

标签: php curl

我正在尝试使用PHP CURL从Web服务器下载一个.exe文件到PC,使用CURL自动登录Web服务器。我遇到的问题是文件被写入浏览器窗口而不是要求用户保存或运行该文件。我正在使用下面的代码,我该如何解决这个问题让它像我想要的那样工作?

$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);

2 个答案:

答案 0 :(得分:3)

您应该设置标题,以便浏览器知道它必须显示保存对话框。

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

另外,请注意Content-Type标题应在Content-Disposition之前。

答案 1 :(得分:2)

将以下代码添加到您的代码中:

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

...并将curl_exec($ch)替换为$response = curl_exec($ch);,因此可以使用file_put_contents() fwrite()种方法将$ response内容保存到本地文件中。