duanluo5096 2013-01-30 23:02
浏览 73
已采纳

在两个不同的服务器上通过getJSON调用在PHP中设置cookie

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?

  • 写回答

2条回答 默认 最新

  • doupu7651 2013-01-31 00:22
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算