PHP:cURL:不能同时登录和下载文件

时间:2013-01-01 18:13:26

标签: php curl

基本上,我有一个登录网站的脚本,并下载文件。非常坦率的。不幸的是,我的代码中缺少一些阻止它正常工作的东西。

当我运行它时,我得到一个输出到我的文件的html页面,如果我试图访问文件链接而不登录,这正是我在浏览器中得到的;访问被拒绝,您必须登录等。

但是,如果我通过注释掉文件下载请求来自行运行脚本的第一部分,然后完整地重新运行脚本,我可以按照自己的意愿下载文件,所以我知道它是在某种意义上工作。当我运行整个脚本时,它似乎并不想让我登录。

// Log me in

curl_setopt($handle, CURLOPT_URL, $login_url); 
curl_setopt($handle, CURLOPT_REFERER, $admin_url);
curl_setopt($handle, CURLOPT_COOKIEJAR, $Cookie_Location);
curl_setopt($handle, CURLOPT_COOKIEFILE, $cookie); 
curl_setopt($handle, CURLOPT_TIMEOUT, 60); 
curl_setopt($handle, CURLOPT_FOLLOWLOCATION, 1); 
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1); 

// Grab the file

curl_setopt($handle, CURLOPT_URL, $csv_loc);
curl_setopt($handle, CURLOPT_FILE, $csv_handle); 

echo $response = curl_exec($handle);

curl_close($handle);

所以我可以登录,然后重新运行脚本并下载文件,但我不能同时执行这两个操作。我已经尝试了各种不同的额外卷曲选项,如COOKIEJAR和COOKIEFILE,以及FOLLOWLOCATION和REFERER,这是我唯一的预感,为什么我的代码不起作用。我的“抓取文件”代码中的某些内容要么是我的登录,要么就是我没有登录。

编辑:已解决。

我决定加入解决方案,以便其他人避免犯同样的错误。

我需要做的就是分开我的要求,就像这样;

// Log me in

curl_setopt($handle, CURLOPT_URL, $login_url); 
curl_setopt($handle, CURLOPT_REFERER, $admin_url);
curl_setopt($handle, CURLOPT_COOKIEJAR, $Cookie_Location);
curl_setopt($handle, CURLOPT_COOKIEFILE, $cookie); 
curl_setopt($handle, CURLOPT_TIMEOUT, 60); 
curl_setopt($handle, CURLOPT_FOLLOWLOCATION, 1); 
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1); 

echo $response = curl_exec($handle);

// Grab the file

curl_setopt($handle, CURLOPT_URL, $csv_loc);
curl_setopt($handle, CURLOPT_FILE, $csv_handle);

curl_exec($handle);

curl_close($handle);

首先curl_exec将我登录到该站点,然后第二个抓取并下载我的文件。然后我关上手柄。

1 个答案:

答案 0 :(得分:3)

如果这正是您正在使用的代码,那么:

// Log me in
curl_setopt($handle, CURLOPT_URL, $login_url); 

// Grab the file
curl_setopt($handle, CURLOPT_URL, $csv_loc);

echo $response = curl_exec($handle);
curl_close($handle);

您正在重新定义您的网址。您无法在一个请求中向一个URL(登录)和GET(获取文件)发送POST,您需要发送2个单独的请求。

除非,否则您的登录表单会立即将文件作为回复。

相关问题