Use cookie with cURL PHP


Use cookie with cURL PHP

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

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

Allen,在像你这样的情况下,当我用curl登录时遇到麻烦时,我通常做的是使用firefox的Live Http Headers来记录我的请求,然后使用curl 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"
);
然后,使用headerscurl:
curl_setopt($ch, CURLOPT_HTTPHEADER, $myHeaders );

指出:
1-不需要CURLOPT_COOKIEJARCURLOPT_COOKIEFILE
这几乎适用于我试过的所有网站。
3-一些cookie可能会在一段时间后过期,其他的,像谷歌,永远不会过期。