【问题标题】:Unable to save the session while making multiple requests using CURL使用 CURL 发出多个请求时无法保存会话
【发布时间】:2018-03-03 03:19:36
【问题描述】:

我正在尝试使用 CURL 打开一个 html 页面,然后提取验证码图像 URL 并将图像保存为 PNG。我可以同时执行这两项操作,但屏幕上显示的图像和保存的图像文件不同。我该如何解决这个问题?

//Get page contents first
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://www.gstsearch.in/track-provisional-id.html");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookiefile.txt");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookiefile.txt");


$pageContent = curl_exec ($ch);
$errNo = curl_errno($ch); //CURL error code
curl_close ($ch);


if($errNo == 0) {
    $imgURL = getCaptcha($pageContent); //Get captcha image
    saveCaptcha($imgURL); //Save the captcha image as PNG
}
else {
    $errorMsg = curl_strerror($errNo);
    echo "CURL error ({$errNo}):\n {$errorMsg}";
}




function getCaptcha($html) {
    $dom = new DOMDocument();
    @$dom->loadHTML($html);
    $captchaImg = $dom->getElementById('captchacode');
    $imgSrc = $captchaImg->getAttribute('data-src');

    //URL of the current captcha image
    $imgURL = "https://www.gstsearch.in/{$imgSrc}";
    echo "<img src={$imgURL}>";

    return $imgURL;
}

function saveCaptcha($url) {
    $fp = fopen ("captcha.png", 'w+');

    $sc = curl_init();
    curl_setopt($sc, CURLOPT_URL, $url);
    curl_setopt($sc, CURLOPT_SSL_VERIFYPEER, FALSE);

    curl_setopt($sc, CURLOPT_COOKIEFILE, "cookiefile.txt");
    curl_setopt($sc, CURLOPT_COOKIEJAR, "cookiefile.txt");

    curl_setopt($sc, CURLOPT_FILE, $fp);
    curl_setopt($sc, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($sc, CURLOPT_USERAGENT, 'Mozilla/5.0');
    curl_exec($sc);
    curl_close($sc);
    fclose($fp);
}

更新:我根据建议更新了代码,但仍然发生同样的事情。我错过了什么?

【问题讨论】:

  • 您没有保留任何会话信息,因此您的第二个 cURL 请求将获得与您的第一个请求无关的图像。您应该存储并使用您在第一个请求中返回的 cookie。
  • @jeoren,查看我更新的问题。

标签: php curl captcha


【解决方案1】:

我同意@jeroen,远程站点认为有两个不同的用户:一个发布信息,另一个正在检索 CAPTCHA :)

您可以使用此存储(和重复使用)session_id

//this is to pass `session_id` between requests
curl_setopt($ch, CURLOPT_COOKIEFILE, $some_path . 'cookie.txt');
//this is to store cookies for future requests, i.e. if you want to retain your session
curl_setopt($ch, CURLOPT_COOKIEJAR, $some_path . 'cookie.txt');

您应该将它们用于这两个请求。这样网站会认为你是同一个用户,但不是两个不同的用户(就像它现在认为的那样)

【讨论】:

    猜你喜欢
    • 2014-03-24
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    相关资源
    最近更新 更多