简体   繁体   中英

PHP curl get cookies from multiple domains

I set cookies on main.com, but i need to get these cookies from other my domain2.com, how to do this with curl or another ways?

It`s my code in domain2.com/get.php:

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, 'http://main.com');
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($curl, CURLOPT_HEADER, true);  
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 

$data = curl_exec($curl);
curl_close($curl);

preg_match_all('#Set-Cookie: (.*);#U', $data, $matches);   
$cookies = implode(';', $matches[1]);

echo $cookies;

Is it possible?

This is not possible due to the Same origin policy . A browser will never send main.com cookies to domain2.com, and cURL will just act as a new HTTP client visiting main.com; it'll get new cookies, but they won't have anything to do with your visitor.

To have a cross-domain session, you'd need for a visit to one server to establish a session on both. Eg when the user visits main.com, the HTML output contains an empty image to http://domain2.com/setCookie?sess=<main_session_Id> . The script on domain2.com would set the session cookie, with the result being that the client ends up with an identical session cookie on both domains. The domains can then use backend requests, if not on the same machine, to share info.

Cross-domain session management tends to be messy and is fraught with caveats. Look for a well-tested solution rather than making up your own.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM