PHP cookie重定向问题

时间:2013-12-08 19:42:23

标签: php redirect cookies

我不确定问题是什么,但cookie不适用于子域名。有没有办法解决这个问题,还是有更好的方法来设置cookie域?谢谢!

<?php 
ini_set("session.cookie_domain", ".example.com"); 

// Set cookie and redirect when user change city 
if( isset($_POST['city']) && $_POST['city'] != '' ){ 
$cookie_expire = time() + 50400;  
setcookie('city', $_POST['city'], $cookie_expire, '/'); 

header("Location: http://".$_POST["city"].".example.com"); 
die(); 
} 

// Redirect if user selected default city 
if (isset($_COOKIE["city"])) { 
$subdomain = array_shift(explode(".",$_SERVER['HTTP_HOST'])); 

if ($_COOKIE["city"] != $subdomain) { 
    header("Location: http://".$_COOKIE["city"].".example.com"); 
    die(); 
} 
}

2 个答案:

答案 0 :(得分:0)

尝试使用setcookie的$ domain参数。

setcookie('city', $_POST['city'], $cookie_expire, '/', '.example.com'); // With leading dot for old browsers

见这里: http://php.net/setcookie

答案 1 :(得分:0)

如果Cookie路径为http://www.example.com/,请检查Cookie上的路径 并且你重定向到http://www.example.com(注意缺少尾随/)一些浏览器会丢弃cookie - 根据我的经验。