2015-11-24 30 views
1

我正在嘗試使用PHP/curl登錄到一個站點,以便能夠訪問僅可用於網站上註冊用戶的數據。該表格會請求電子郵件,密碼和隱藏的安全值。安全值是隨每個登錄頁面加載隨機生成的。我認爲這是導致我的問題:在下面的腳本中,curl首先請求頁面,代碼解析安全值,然後curl嘗試登錄。但是,正如我使用print_r驗證過的,安全代碼已更改爲第二頁加載。curl中的Cookie和隱藏的安全值

下面是代碼:

$email = urlencode("emailhandleIuse"); 
$password = "myPassword"; 
$loginURL = "https://www.example.com/login/"; 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $loginURL); 
$ch = setCurlParameters($ch); 
$securityCode = curl_exec($ch); 
$securityCode = urlencode(scrape_between($securityCode, "<input type=\"hidden\" name=\"security\" value=\"","\" />")); // gets security value from the page HTML 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, 'email='.$email.'&password='.$password.'&security='.$securityCode); 
curl_exec($ch); 
curl_setopt($ch, CURLOPT_URL, "https://www.example.com/followingpage"); 
$secondPage = curl_exec($ch); 
curl_close($ch); 

function setCurlParameters($ch) { 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); 
    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE); 
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17"); 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 120); 
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10); 
    curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt'); 
    curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt'); 
    curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE); 
    curl_setopt($ch, CURLOPT_UNRESTRICTED_AUTH, TRUE); 
    curl_setopt($ch, CURLOPT_VERBOSE, 0); 
    return $ch; 
} 

function scrape_between($data, $start, $end){ 
    $data = stristr($data, $start); // Stripping all data from before $start 
    $data = substr($data, strlen($start)); // Stripping $start 
    $stop = stripos($data, $end); // Getting the position of the $end of the data to scrape 
    $data = substr($data, 0, $stop); // Stripping all data from after and including the $end of the data to scrape 
    return $data; // Returning the scraped data from the function 
    } 

$ secondPage捲起是一個登錄頁面,因爲我不是張貼我認爲需要的細節後確認。

任何幫助非常感謝。

回答

0

做完第一個請求後,您必須關閉curl句柄,否則cookie不會被存儲到文件中。這就是爲什麼你的第二個請求(登錄)不會將cookie轉發到服務器。

curl_close($ch); 

對於cookie文件,更好地當你從服務器上運行使用完整路徑c:/tmp/cookie.txt(我認爲)。

順便說一句,使用詳細模式,你可以看到自己究竟發生了什麼!

curl_setopt($ch, CURLOPT_VERBOSE, TRUE);