2015-10-04 130 views
0

我需要获取仅在登录时可访问的页面的源代码。但是,当我使用以下代码时,它不能识别我已登录,并且要求我重新登录。使用cookie和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; 

我研究并找到了类似于我的例子,但他们不帮我。当我使用上面的代码时,它不识别我的cookies。

全码:

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

http://stackoverflow.com/questions/10307744/how-to-login-in-with-curl-and-ssl-and-cookies可能的重复 –

回答

0

艾伦,在你们这样的情况,当我遇到麻烦卷曲登录,我通常做的是使用Live Http Headers for firefox登录我的请求,然后用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
2 - 这适用于几乎我试过每一个网站。
3-一些cookie可能在一段时间后过期,其他一些cookie也可能会过期。