curl中的Cookie和隐藏的安全值


Cookies and Hidden Security Values in curl

我正试图使用PHP/ccurl登录到一个网站,以便能够访问该网站上只有注册用户才能使用的数据。该表单要求提供电子邮件、密码和隐藏的安全值。安全值是随每次登录页面加载而随机生成的。我认为这就是我的问题所在:在下面的脚本中,curl首先请求页面,代码解析安全值,然后curl尝试登录。然而,正如我使用print_r验证的那样,第二次加载页面时的安全代码会发生变化。

这是代码:

$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最终成为一个登录页面,因为我在发布了我认为需要的详细信息后没有进行验证。

非常感谢您的帮助。

完成第一个请求后,必须关闭curl句柄,否则cookie将不会存储到文件中。这就是为什么您的第二个请求(登录)没有将cookie转发到服务器。

curl_close($ch);

对于cookie文件,当您从服务器上运行时,最好使用完整路径c:/tmp/cookie.txt(我认为)。

顺便说一句,使用详细模式,你可以亲眼看到实际发生了什么!

curl_setopt($ch, CURLOPT_VERBOSE, TRUE);