php - 使用 cURL 下载文件

标签 php redirect curl server

我正在尝试使用 cURL 下载文件。我收到了文件所在的 URL,但该 url 在到达文件之前进行了重定向。由于某种原因,当我使用 cURL 访问 URL 时,我总是收到注销页面,但是当我直接在浏览器中输入 URL 时,文件就会按预期下载。应下载的文件是 RAR 文件,但我得到的不是该文件,而是错误的登录页面。

这是当前代码:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true); 
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
$result = curl_exec($ch); 

curl_close($ch);

print_r($result);

如您所见,我使用以下代码来允许重定向:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 

但是,如果我使用上述代码,我总是从网站收到错误的登录页面。谁能看到我在这里做错了什么?

这是我从服务器得到的响应:

HTTP/1.1 302 Found
Date: Tue, 26 Jan 2016 15:33:18 GMT
Server: Apache/2.2.3 (Red Hat)
X-Powered-By: PHP/5.3.2
Set-Cookie: PHPSESSID=session_id; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Location: /nl/nl/export/download/t/Mg==/c/MTQ=/
Vary: Accept-Encoding
Content-Length: 0
Content-Type: text/html; charset=UTF-8

最佳答案

尝试使用此代码

$url = "www.abc.com/xyz";//your url will come here
$fp = fopen ('test.txt', 'w+');
$ch = curl_init(str_replace(" ","%20",$url));
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_FILE, $fp); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch); 
curl_close($ch);
fclose($fp);

关于php - 使用 cURL 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34998100/

相关文章:

php - 如何隐藏空元素?

重定向 RTMP 请求

php - 如果在 mysql 表中找不到项目,如何重定向到另一个页面?

html - 我如何使用 .htaccess 将不同的语言重定向到不同的页面?

PHP 函数中的 JavaScript jQuery

php - 将 php 多维数组分配给 javascript 数组

linux - curl chunky 解析器错误

python - 使用 curl 与 Python 请求

php - 如何找到数组中哪些列包含所有数字

ruby-on-rails - 将 curl 命令转换为 httparty