将cookie与cURL PHP一起使用

时间:2015-10-04 12:47:50

标签: php curl cookies

我需要获取只有在我登录时才能访问的页面的源代码。但是,当我使用以下代码时,它不会识别我已登录,并询问我重新登录。

$opts = array('http' => array('header'=> 'Cookie: ' . $COOKIEFILE."\r\n"));
$context = stream_context_create($opts);
$file = file_get_contents('http://www.example.com/', false, $context);
echo $file;

我研究过并发现了类似于我的例子,但他们并没有帮助我。当我使用上面的代码时,它无法识别我的cookie。

完整代码:

$USERNAME = 'myEmail';
$PASSWORD = 'myPassword';
$COOKIEFILE = tempnam ("/tmp", "CURLCOOKIE");

$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, $COOKIEFILE);
curl_setopt($ch, CURLOPT_COOKIEFILE, $COOKIEFILE);
curl_setopt($ch, CURLOPT_HEADER, 0);  
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);

curl_setopt($ch, CURLOPT_URL, 
  'https://accounts.google.com/ServiceLogin?hl=en&service=alerts&continue=http://www.google.com/alerts/manage');
$data = curl_exec($ch);

$formFields = getFormFields($data);

$formFields['Email']  = $USERNAME;
$formFields['Passwd'] = $PASSWORD;
unset($formFields['PersistentCookie']);

$post_string = '';
foreach($formFields as $key => $value) {
    $post_string .= $key . '=' . urlencode($value) . '&';
}

$post_string = substr($post_string, 0, -1);

curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/ServiceLoginAuth');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);

$result = curl_exec($ch);
$ch = curl_init ("http:/example.com");
curl_setopt ($ch, CURLOPT_COOKIEFILE, $COOKIEFILE); 
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
var_dump($output);

1 个答案:

答案 0 :(得分:0)

Allen,在您这样的情况下,当我使用curl登录时遇到问题,我通常使用Live Http Headers for firefox来记录我的请求,然后使用curl {的请求标头{1}},CURLOPT_HTTPHEADER将包含在cookies

<强>流量:

使用您的浏览器登录网站,记录后,使用headers记录任何请求,将请求复制并粘贴到Live Http Headers for firefox,例如:

array

然后,将$myHeaders = array( "Host: stackoverflow.com", "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0", "Accept: application/json, text/javascript, */*; q=0.01", "Accept-Language: en-US,en;q=0.5", "Accept-Encoding: gzip, deflate", "DNT: 1", "Content-Type: application/x-www-form-urlencoded; charset=UTF-8", "X-Requested-With: XMLHttpRequest", "Referer: http://stackoverflow.com/questions/32933636/use-cookie-with-curl-php", "Content-Length: 482", "Cookie: mycookie :)", "Connection: keep-alive", "Pragma: no-cache" ); headers

一起使用
curl

注意:
1-无需curl_setopt($ch, CURLOPT_HTTPHEADER, $myHeaders ); CURLOPT_COOKIEJAR
2-这适用于我尝试过的几乎所有网站 3-一些cookie可能会在一段时间后过期,其他一些像谷歌一样,永不过期。