Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

sample code

in the second domain readcookie.php file

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

if(isset($_COOKIE['user'])){
        echo $_COOKIE['user'];
    }
    else{
        setcookie('user','a2345',0);
        echo $_COOKIE['user'];
    }
like image 215
manashb Avatar asked Jan 12 '12 11:01

manashb


2 Answers

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

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.

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

like image 182
Reinstate Monica Cellio Avatar answered Sep 21 '22 13:09

Reinstate Monica Cellio


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

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.

like image 22
Semir Avatar answered Sep 18 '22 13:09

Semir