简体   繁体   English

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

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

Suppose i have a cookie set in first.com say user. 假设我在first.com中设置了一个cookie设置用户。 Now i want to read that cookie in second.com through javascript and ajax. 现在我想通过javascript和ajax在second.com中读取该cookie。 But it is not working.I have got xmlHttp.status=0. 但它没有用。我有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'];
    }

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. 您显然需要完全访问这两个域才能执行此类操作。

Your problem is that browsers wont let javascript to access different domain. 您的问题是浏览器不会让javascript访问不同的域。 Add: 加:

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

lines to the beginning of cookie.php and it'll work. 行到cookie.php的开头,它会工作。 Still, you wont get the cookie (or at least in Chrome). 不过,你不会得到cookie(或者至少在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. 似乎chrome为javascript创建了一个新会话,并且不会让该会话访问以前的cookie。 Like HttpOnly. 像HttpOnly一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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