首页 > 解决方案 > PHP cURL - 登录并使用 cookie 进行下次运行

问题描述

我的代码:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(!empty($post)){
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
}
else{
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
}
curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
$headers = array();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$page = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}

$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($page, 0, $header_size);
$body = substr($page, $header_size);
curl_close($ch);
return $body;

效果很好!我只是想知道我用于多次运行的这些 cookie 能持续多久?

我怎么能检查呢?

标签: phpcurl

解决方案


像这样的东西(从https://stackoverflow.com/a/9797313/593807借来的)应该给你 cookie 的到期日期。

preg_match_all('/.*?expires=(?P<expires>[^;]*).*?$/im', $header, $matches);
var_dump($matches);

你应该得到匹配的日期 - -1 的结果意味着没有正则表达式匹配,可能是因为在标题中没有设置过期。

到期日期是一个可选的标题。


推荐阅读