我只是尝试使用curl从网站上获取一些cookie,我已经阅读了与此相关的数千个主题,问题几乎在所有与文件路径相关的情况下(必须是绝对的。
我尝试了几件事,但我找不到我的cookies没有写的原因。我在这里使用代码:
$cookieDir = 'tmp/cookies.txt';
$options = Array(
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_URL => $url,
CURLOPT_COOKIEJAR => realpath($cookieDir),
CURLOPT_COOKIEFILE => realpath($cookieDir)
);
$ch = curl_init();
curl_setopt_array($ch, $options);
ob_start();
$data = curl_exec($ch);
ob_end_clean();
curl_close($ch);
一些注释:
谢谢你们
答案 0 :(得分:0)
我认为您必须将CURLOPT_POST
选项设置为true才能获取Cookie,以下内容适用于我:
$cookieDir = '<ABSOLUTE_PATH>/cookie.txt';
$options = array (
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_URL => '<URL>',
CURLOPT_COOKIEJAR => $cookieDir,
CURLOPT_COOKIEFILE => $cookieDir,
CURLOPT_POST => TRUE,
CURLOPT_FOLLOWLOCATION => TRUE,
);
$ch = curl_init();
curl_setopt_array($ch, $options);
$data = curl_exec($ch);
您还应该可以通过在请求中设置CURLOPT_HEADER
来获取标头中的所有Cookie:
$cookieDir = '<ABSOLUTE_PATH>/cookie.txt';
$options = array (
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_URL => '<URL>',
CURLOPT_POST => TRUE,
CURLOPT_HEADER => TRUE,
CURLOPT_FOLLOWLOCATION => TRUE
);
$ch = curl_init();
curl_setopt_array($ch, $options);
$data = curl_exec($ch);
// check the return value for `Set-Cookie` header
$cookies = array();
preg_match('/^Set-Cookie:\s*([^\r\n]*)/mi', $data, $cookies);
// $cookies[0] now contains any `Set-Cookie:` header
答案 1 :(得分:0)
该网站不允许我获取他们的cookie,为了得到他们我必须让它认为我是一个使用这个额外参数的普通浏览器:
$header = array (
'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0',
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3',
'Connection: keep-alive'
);
然后在$ options
$options = array (
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_URL => $url,
CURLOPT_COOKIEJAR => realpath($cookieDir),
CURLOPT_COOKIEFILE => realpath($cookieDir),
CURLOPT_HTTPHEADER => $header
);
即使它是一个奇怪的案例,我希望它能帮助别人=)