Search code examples
phpjquerycookiessetcookie

Set cookie in PHP from a getJSON call on two different servers


I have two servers, 'www.domain.local' and 'api.domain.local'. I want to set a cookie in a script on the api server that is called from the www. Chrome does not let me do that (didn't try other browsers yet)

my PHP code:

header("Access-Control-Allow-Origin:*");
echo json_encode(array("cookie"=>print_r($_COOKIE,true)));
setcookie("test","ok",time()+24000*3600,"/",".domain.local");

in my jQuery:

$.getJSON("http://api.domain.local/test.php",{
  command:"setcookie"
},function(fb){
  alert(fb.cookie);
});

The PHP is first returning the cookies it has, the first run this should be zero, and it is. In the header of the PHP script I see the following:

Set-Cookie:test=ok; expires=Tue, 27-Oct-2015 22:52:52 GMT; path=/; domain=.domain.local X-Powered-By:PHP/5.3.14

Which is what I expect. But the cookie isn't set. When I run the jQuery again I am expecting the cookie to be set (get an alert with the print_r of $_COOKIE), but I get nothing. One thing I noticed in the 'cookies' tab of the network resources in the debug part of Chrome is that the expiry was set as "Invalid Date". If I run the PHP script directly I don't have this problem though.

Is it possible to set a cookie in a PHP script called from jQuery and if so, how?


Solution

  • Let's see, set a cookie on a different domain to the one that the page is loading on and in PHP from jQuery

    Someone might post how you're supposed to do it. I might just cheat.

    www.domain.local/test.html includes

    $.getScript("http://api.domain.local/test.php?dowhat=setcookie");
    

    api.domain.local/test.php is

    <?php
    switch ($_GET['dowhat']){
        case 'showcookie':
            print_r($_COOKIE);
            break;
        case 'setcookie':
            setcookie("test",date('Y m D H:i:s'),time()+24000*3600,"/");
            break;
    }
    header("Content-type: application/javascript"); // may as well, it expects this
    die;
    

    Now go to http://api.domain.local/test.php?dowhat=showcookie

    Array ([test] => 2013 01 Thu 00:20:52 ) 
    

    Ta-da!

    P.S. I wouldn't advise doing it this simply if you need it to be set without someone naughty being able to cheat too.