Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending cookies stored on $_COOKIE global using PHP curl

Tags:

php

curl

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?

like image 979
Mike Montesines Avatar asked Oct 23 '12 10:10

Mike Montesines


People also ask

How do you curl cookies?

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.

How do I enable my cookies in curl?

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.


3 Answers

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 );
like image 161
Robbie Avatar answered Sep 28 '22 08:09

Robbie


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

like image 24
Tim Smith Avatar answered Sep 28 '22 08:09

Tim Smith


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']);
like image 20
Sebastian Zartner Avatar answered Sep 28 '22 09:09

Sebastian Zartner