且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何设置一个cookie,然后在PHP中重定向?

更新时间:2023-09-28 23:28:28

如果您有人类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.