2017-01-24 110 views
0

我想創建一個php腳本,它登錄到一個網站,然後導航到(可能多個)需要用戶登錄才能看到它們的網頁。我想我已經成功使用cURL登錄,但是我不知道如何在登錄後「保持登錄狀態」來閱讀文件內容。我懷疑我的問題與使用相同的cookie文件有關,但我不確定。這是我目前擁有的:PHP腳本在登錄後讀取html

<? 
//login form action url 
$url="https://randomwebsite.com/users/sign_in"; 
$postinfo = "utf8=%E2%9C%93&authenticity_token=ncgU2234iEMObg3334d3Iag%2BPBrmEerybFZ3X2fvVsUTmpjkPDQMgteeGlVDxFRfHjmHbvIYaTchvM2psKFzI%2BAHIpCw%3D%3D&user%5Botp_attempt%5D=step_1&user%5Blocale%5D=en&user%5Blogin%5D=randomuser&user%5Bpassword%5D=123456"; 

$cookie_file_path = "cookies1.txt"; 

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_HEADER, false); 
curl_setopt($ch, CURLOPT_NOBODY, false); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 

curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path); 
curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie_file_path); 

//set the cookie the site has for certain features, this is optional 
curl_setopt($ch, CURLOPT_COOKIE, "cookiename=0"); 
curl_setopt($ch, CURLOPT_USERAGENT, 
    "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_REFERER, $url); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0); 

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $postinfo); 
$curlexecresponse = curl_exec($ch); 
//echo("\ncurlexecresponse: " . $curlexecresponse); 

// Now that we're logged in we can finally read the web pages we want to... 
$url2 = "url to members only page"; 
curl_setopt($ch, CURLOPT_URL, $url2); 
curl_setopt($ch, CURLOPT_POST, 0); 

$data = curl_exec($ch); 

echo("\n\n data is: " . $data); // this is empty 

curl_close($ch); 
?> 

如何在登錄後在頁面中讀取HTML?

+0

看看這個幫助http://stackoverflow.com/questions/13020404/keeping-session-alive-with-curl-and -php – webDev

+0

如果切換到使用Guzzle,這可能會更容易。 – aalaap

回答

0

你需要登錄後發送的每個請求的餅乾英寸

$url2 = "url to members only page"; 
//Add this line 
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path); 
curl_setopt($ch, CURLOPT_URL, $url2); 
curl_setopt($ch, CURLOPT_POST, 0); 
+0

由於某種原因,即使添加了你提到的行,curl_exec()響應仍然會回到空白 – user2804881

+0

嘿,我注意到我的行中的捲曲對象是錯誤的,請使用$ ch而不是$ ch。我編輯了答案。 –

+0

如果還沒有回來嘗試「echo curl_error($ ch)」來查看是否有任何錯誤被拋出。 –