尝试使用PHP的CURL获取cookie

I'm just trying to obtain some cookies from a website using curl, I've read thousands of topics related with this, the problem was in almost every case related to the path to the file (which must be absolute).

I tried several things but I can not 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:

  1. The file exists
  2. realpath($cookieDir) is writable
  3. I'm getting the website in $data without troubles

Thank you guys

I think you must set the CURLOPT_POST option to true to get the cookies, the following worked for me:

$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 should also be able to 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*([^
]*)/mi', $data, $cookies); 
// $cookies[0] now contains any `Set-Cookie:` header

It was the website who was not allowing me to get their cookies, to get them I had to made it think I'm a ordinary 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 though its a strange case I hope it will help others =)