setting cookie through curl

2019-07-17 23:59发布

问题:

I am trying to set cookie through cURL in PHP but it fails. my php code looks like this

$ch=curl_init();
$url="http://localhost/javascript%20cookies/test_cookies.html";
curl_setopt($ch, CURLOPT_COOKIE, 'user=1');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec($ch);
curl_close($ch);
echo $contents;
?>

the file test_cookies.html contains javascript that checks for a cookie and if it finds it dispalys the content with additional user content. but when i use the above script it displays the contents of the page test_cookies.html but not with the additional user content which means that it is not setting the cookie.

i tried writing another script like this

<?php
header("Set-Cookie:user=1");
header("Location:test_cookies.html");
?>

this works and sets the cookie and shows the additional user content too. I also tried using

curl_setopt($ch,CURLOPT_COOKIEFILE,"cookie.txt");
curl_setopt($ch,CURLOPT_COOKIEJAR,"cookie.txt");

this is writing the cookie information to the file but not reading it when fetching the page. can somebody help?

回答1:

Since javascript conducts the check in the browser, you should set the cookie before sending the output to the browser. So you need to combine both scripts:

$ch=curl_init();
$url="http://localhost/javascript%20cookies/test_cookies.html";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec($ch);
curl_close($ch);
header("Set-Cookie:user=1");
echo $contents;

Explanation:
Please note that we are looking at two transfers here:

  1. data is fetched by curl, and then
  2. it is sent to the browser.

This is a special case where you are using curl to get the content from localhost, but in real-life uses you'd use curl to get content from a 3rd host.

If you receive different content based on whether a cookie is sent in the request or not, then you should set the cookie with curl. In most cases you can then send the content with no additional tweaking to the browser. But here, you make the decision with checking for a cookie in the browser, so you don't need the first cookie setting, and you do need the second one.



回答2:

JavaScript will not work by getting page from curl.