Setting a cookie before a redirect

时间秒杀一切 提交于 2021-02-10 09:25:33

问题


I'm attempting to set a cookie just before a header redirect but it is not working. I have read that setting the cookie after the header redirect line should solve the problem, but I am having no luck. Similarly, a post here previously suggested that if you were using a 'human URL' in the location redirect, you should use '/' in the path parameter of the cookie. This has also been done with no luck.

header("Location: $url" . $params);
setcookie('cartstlang', 'lang', 0, '/', '', FALSE, FALSE);
setcookie('cartstdb', 'db', 0, '/', '', FALSE, FALSE);

Also note, I have tested this by commenting out the header redirect and then clicking on an link to change pages. The cookies then appeared fine on a var_dump().

I am developing on XAMPP with PHP 5.3+. I have tested in both IE 8 and Firefox 4.

Any help would be great. Thanks.


回答1:


The setcookie code should come before the header code and make sure you do an exit() after to stop any output.

Also are you sure it's going to the same domain (there is a difference between http://site.com and http://www.site.com)? Try setting the domain option to .site.com in the setcookie so it can be accessed across all subdomains.




回答2:


try this

$value = 'something from somewhere';

setcookie("TestCookie", $value);




echo $_COOKIE["TestCookie"];
echo $HTTP_COOKIE_VARS["TestCookie"];

// Another way to debug/test is to view all cookies
print_r($_COOKIE);

and post back the reply what do you see. Also make sure cookies are enabled.



来源:https://stackoverflow.com/questions/6277032/setting-a-cookie-before-a-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!