如何使用 php 和 javascript 从不同的域获取 cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8834436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:44:00  来源:igfitidea点击:

how to get cookies from a different domain with php and javascript

phpjavascriptajaxcookies

提问by manashb

Suppose i have a cookie set in first.com say user. Now i want to read that cookie in second.com through javascript and ajax. But it is not working.I have got xmlHttp.status=0.

假设我在 first.com 中设置了一个 cookie 说用户。现在我想通过javascript和ajax读取second.com中的cookie。但它不起作用。我有 xmlHttp.status=0。

sample code

示例代码

in the second domain readcookie.php file

在第二个域 readcookie.php 文件中

var xmlHttp;
    function createXMLHttpRequest(){
        if(window.ActiveXObject)
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        if(window.XMLHttpRequest)
            xmlHttp=new XMLHttpRequest();
    }
    function readcookie(){

        createXMLHttpRequest(); 
        xmlHttp.open("GET","http://www.first.com/cookie.php",true);
        xmlHttp.onreadystatechange=getcookie;
        xmlHttp.send(null);
    }
    function getcookie(){
        if(xmlHttp.readyState==4){
            if(xmlHttp.status==200){
                var reply=xmlHttp.responseText;
                if(reply){
                    alert(reply);
                }
            }
            else
                alert(xmlHttp.status);
        }
    }

in the first domain cookie.php file

在第一个域 cookie.php 文件中

if(isset($_COOKIE['user'])){
        echo $_COOKIE['user'];
    }
    else{
        setcookie('user','a2345',0);
        echo $_COOKIE['user'];
    }

回答by Reinstate Monica Cellio

You can't read cookies from another domain - end of.

您无法从另一个域读取 cookie - 结束。

The only way I can think of is to add some code to the 2nd domain that gets the cookies for you and then to place this in a page on the 1st domain, in an iframe.

我能想到的唯一方法是将一些代码添加到为您获取 cookie 的第二个域中,然后将其放置在 iframe 中的第一个域上的页面中。

You obviously need full access to both domains to be able to do this kind of thing.

您显然需要对两个域的完全访问权限才能执行此类操作。

回答by Semir

Your problem is that browsers wont let javascript to access different domain. Add:

您的问题是浏览器不会让 javascript 访问不同的域。添加:

header('Content-type: text/html');    
header('Access-Control-Allow-Origin: *');   

lines to the beginning of cookie.php and it'll work. Still, you wont get the cookie (or at least in Chrome). I couldnt yet figure out why. It seems as if chrome creates a new session for the javascript and wont let that session access previous cookies. Like HttpOnly.

行到 cookie.php 的开头,它会起作用。不过,你不会得到 cookie(或至少在 Chrome 中)。我还想不通为什么。似乎 chrome 为 javascript 创建了一个新会话,并且不会让该会话访问以前的 cookie。像 HttpOnly。