PHP CURL 将 cookie 保存到 cookiejar 中但不使用它

问题描述 投票:0回答:2

我有一个 PHP 脚本,它使用 CURL 来通过简单的登录页面登录网站。它向网站发送初始请求,并查看网站是否已登录(由于 cookie)或是否出现登录页面 - 如果出现,则登录。

但是,最近我注意到,每次脚本运行时,它都不会登录。使用 VERBOSE 深入研究标头表明,COOKIEFILE/COOKIEJAR 中的 cookie 从未被使用,仅使用该特定站点收到的 cookie会议。如果我在运行过程中手动将 cookie 添加到 cookiejar(以前可以正常工作),那么它就不再工作了,因为 COOKIEFILE 中的 cookie 并未实际使用。

这种情况在本地和生产服务器上都会发生,这意味着它似乎不是系统问题。我为其他登录页面创建了测试版本,结果相同。 我使用 cookie 文件的完整路径(使用 cookie 更新,只是未使用)并使用curl_close()。

以下是CURL函数:

private function curlPage($url, $postParameters) {
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postParameters);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_COOKIEJAR, __DIR__.'/cookie.txt');
    curl_setopt($ch, CURLOPT_COOKIEFILE, __DIR__.'/cookie.txt');
    curl_setopt($ch, CURLOPT_ENCODING, '');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_POSTREDIR, 3);
    if ($this->verbose == 1) curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
    curl_setopt($ch, CURLOPT_TIMEOUT, $this->defaultTimeout); 
    curl_setopt($ch, CURLOPT_USERAGENT, $this->useragent);
    $pageResponse = curl_exec($ch);
    curl_close($ch); 
    return $pageResponse;
}

以下是 CURL 请求对主页的详细响应,应该检查它是否已登录。由于该站点是客户端的,所以我对其进行了编辑。

* Rebuilt URL to: *********
* Hostname was NOT found in DNS cache
*   Trying : *********...
* Connected to : ********* (*********) port 80 (#0)
> GET / HTTP/1.1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/600.6.3 (KHTML, like Gecko) Version/8.0.6 Safari/600.6.3
Host: *********
Accept: */*

< HTTP/1.1 200 OK
< Date: Wed, 20 Jul 2016 20:42:22 GMT
< Content-Type: text/html
< Transfer-Encoding: chunked
< Connection: keep-alive
< Keep-Alive: timeout=15
< Vary: Accept-Encoding
< Expires: Mon, 26 Jul 1980 00:00:00 GMT
< Pragma: no-cache
< Cache-Control: no-cache, no-store, must-revalidate
* Server ********* is not blacklisted
< Server: *********
< 

可以看出 - 尽管有可用的 COOKIEFILE,但看不到 cookie。

任何帮助将不胜感激。

php curl cookies
2个回答
8
投票

首先您必须确保

__DIR__
具有写权限。

第二个是运行代码时。您可以检查

cookie.txt
文件是否已创建。

第三,您必须在所有会话中使用一个 cookie。这样受害者就知道您已登录。

并尝试我的来源

$cookies = tempnam('/tmp','cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookies); 
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookies);

0
投票

您需要的是以下选项:

// 1 = Do not use cookies from the previous session.
curl_setopt($ch, CURLOPT_COOKIESESSION, 0); 

查看更多https://curl.se/docs/http-cookies.html

© www.soinside.com 2019 - 2024. All rights reserved.