如何设置一个cookie,然后在PHP中重定向? [英] How can I set a cookie and then redirect in PHP?

查看:273
本文介绍了如何设置一个cookie,然后在PHP中重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过一些处理之后,我想为用户输入设置一个cookie值,然后将它们重定向到一个新页面。但是,cookie未设置。如果我注释掉重定向,那么cookie设置成功。我认为这是一个头部问题的某种。这种情况的最佳解决方法是什么?

  if($ form_submitted){
...
setcookie('type_id',$ new_type_id,time()+ 60 * 60 * 24 * 30);
header(Location:$ url);
exit;
}

注意setcookie返回 true 编辑:我使用的是Unix / Apache / MySQL / PHP / p>

解决方案

如果您有人类URL或子文件夹(如www.domain.com/path1/path2/),那么必须设置cookie

  if($ form_submitted){
.. 。
setcookie('type_id',$ new_type_id,time()+ 60 * 60 * 24 * 30,'/');
header(Location:$ url);
exit;
}

从PHP手册:



cookie可用的服务器上的路径。如果设置为
'/',则cookie将在整个域中可用
。如果设置为
'/ foo /',那么cookie只能是/ foo /目录
中的
和所有子目录,例如
/ foo / bar /域。默认的
值是
设置cookie的当前目录。



After doing a bit of processing, I want to set a cookie value to user input and then redirect them to a new page. However, the cookie is not getting set. If I comment out the redirect, then the cookie is set successfully. I assume this is a header issue of some sort. What is the best workaround for this situation?

if($form_submitted) {
    ...
    setcookie('type_id', $new_type_id, time() + 60*60*24*30);
    header("Location: $url");
    exit;
}

Note that setcookie returns true in either case and I get no errors/warnings/notices.

EDIT: I am using Unix/Apache/MySQL/PHP

解决方案

If you have human urls or subfolders (like www.domain.com/path1/path2/), then you must set cookie path to / to work for all paths, not just current one.

if($form_submitted) {
    ...
    setcookie('type_id', $new_type_id, time() + 60*60*24*30, '/');
    header("Location: $url");
    exit;
}

From PHP manual:

The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain . If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain . The default value is the current directory that the cookie is being set in.

这篇关于如何设置一个cookie,然后在PHP中重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆