Trying to get cookies with PHP CURL
I'm just trying to get some cookies from a site using curl, I have read thousands of threads related to this, the problem was in almost every case related to the file path (which should be absolute).
I have tried several things, but I cannot find the reason why my cookies are not being written. Here I go with the code:
$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);
Some annotations:
- File exists
- realpath ($ cookieDir) writable
- I am getting site in $ data with no problem
Thanks guys,
source to share
I think you should set the parameter CURLOPT_POST
to true to receive cookies, for me this worked:
$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);
You can also get all cookies from the header by setting CURLOPT_HEADER
in your request:
$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
source to share
It was a website that was preventing me from getting their cookies, in order to get them I had to think I was a normal browser using this extra parameter:
$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'
);
Then in $ options
$options = array (
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_URL => $url,
CURLOPT_COOKIEJAR => realpath($cookieDir),
CURLOPT_COOKIEFILE => realpath($cookieDir),
CURLOPT_HTTPHEADER => $header
);
Even if it's a weird case, I hope it helps others =)
source to share