使用cURL下载文件

使用cURL下载文件

本文介绍了使用cURL下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用cURL下载一个文件。我收到了文件所在的URL,但url在到达文件之前进行重定向。由于某种原因,当我使用cURL访问URL时,我总是收到注销页面,但是当我直接在浏览器中输入URL时,文件只是按照它应该下载的。

I am trying to download a file with cURL. I have received an URL where the file is located, but the url makes an redirect before reaching the file. For some reason I always receive the logout page when I access the URL with cURL, but when I enter the URL directly in my browser the file just downloads as it is supposed to. The file that should be downloaded is a RAR file, but instead of the file I get the incorrect login page.

这是目前的代码:

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

正如你所看到的,我使用下面的代码来允许重定向:

As you can see I am using the following code to allow the redirects:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

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

But I always receive the incorrect login page from the website if I use the above code. Can anyone see what I am doing wrong here ?

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

This is the reponse I get from the server:

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


推荐答案

p>

Try with this code

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

这篇关于使用cURL下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 09:33