2015-10-04 127 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也可能會過期。