0

I have used CURL with PHP, please check the below code

$cookie = "cookies.txt";
file_put_contents($cookie, "");
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);

After that I opened the cookies.txt file, in that the cookies are stored.

Now how do I read that file to get required content.

I have tried to read the file using readfile file_get_contents but no use at all, these are just returning empty string.

Please help me out.

Thanks in advance

Sathvik Chinnu
  • 565
  • 1
  • 7
  • 23

1 Answers1

1

CURL writes the cookies to file at the end of its session. Your problem could be that you're accessing the cookie file before CURL has written the cookies.

The possible fix is to end the CURL session before you try to read from the cookie file:

curl_easy_cleanup($ch);
...
$cookie_text = file_get_contents("cookies.txt");

See the docs.

As a clean alternative, just grab the cookies from the response directly, without going through the cookies.txt file. The code below will put the cookies in an array for you:

preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $response, $matches);
$cookies = array();
foreach($matches[1] as $item) {
    parse_str($item, $cookie);
    $cookies = array_merge($cookies, $cookie);
}

Code taken from this accepted answer:

Community
  • 1
  • 1
BeetleJuice
  • 39,516
  • 19
  • 105
  • 165