I have two site dev1.test.com and dev2.test.com.
These are two sites running on different servers. dev1.test.com is where I logged in and I have cookies set to *.test.com to validate if the user is logged.
Now on dev2.test.com, I want to check if the current user is logged-in by sending a PHP CURL request to dev1.test.com. In my curl request, I want to include the contents of $_COOKIE (where it has the cookie information of *.test.com) to this curl request.
How should I do that in php curl?
Cookies are passed to Curl with the --cookie "Name=Value" command line parameter. Curl automatically converts the given parameter into the Cookie: Name=Value request header. Cookies can be sent by any HTTP method, including GET, POST, PUT, and DELETE, and with any data, including JSON, web forms, and file uploads.
By default, curl doesn't send any cookies but you can add your own cookies via the -b 'name=value' command line argument. To save cookies from the response to a file, use the -c file option. To load cookies from a file, use the -b file option.
As you have a wildcard cookie domain, dev2 will also have the same cookies as dev1. So basically you need to say "pass my cookies to the other server through curl.
The curl option you want is "CURLOPT_COOKIE" and you pass in an string of the cookies "name1=value1;name2=value2"
Putting this together (untested - you need to wrap this amongst the other curl functions, of course)
$cookiesStringToPass = '';
foreach ($_COOKIE as $name=>$value) {
if ($cookiesStringToPass) {
$cookiesStringToPass .= ';';
}
$cookiesStringToPass .= $name . '=' . addslashes($value);
}
curl_setopt ($ch, CURLOPT_COOKIE, $cookiesStringToPass );
This is what I'm using to forward $_COOKIE via curl:
$cookie_data =
implode(
"; ",
array_map(
function($k, $v) {
return "$k=$v";
},
array_keys($_COOKIE),
array_values($_COOKIE)
)
);
curl_setopt($ch, CURLOPT_COOKIE, $cookie_data);
Reference: http://php.net/manual/en/function.curl-setopt.php
Instead of working with $_COOKIE
you could also use $_SERVER['HTTP_COOKIE']
, which contains the HTTP header string.
I.e. you just need to write this:
curl_setopt($ch, CURLOPT_COOKIE, $_SERVER['HTTP_COOKIE']);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With