开发者

PHP curl get cookies from multiple domains

开发者 https://www.devze.com 2023-01-23 18:17 出处:网络
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?开发者_开发百科

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. E.g. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消