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

2021-12-21 00:00:00 http-headers cookies php

经过一些处理后,我想为用户输入设置一个 cookie 值,然后将它们重定向到一个新页面.但是,cookie 没有被设置.如果我注释掉重定向,则 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;
}

请注意,无论哪种情况,setcookie 都会返回 true 并且我没有收到任何错误/警告/通知.

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

我使用的是 Unix/Apache/MySQL/PHP

I am using Unix/Apache/MySQL/PHP

推荐答案

如果您有人工 url 或子文件夹(如 www.domain.com/path1/path2/),那么您必须将 cookie 路径设置为/以适用于所有人路径,而不仅仅是当前路径.

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;
}

来自 PHP 手册:

服务器上的路径cookie 将可用.如果设置为'/', cookie 将可用整个域内.如果设置为'/foo/', cookie 只会是在/foo/目录中可用以及所有子目录,例如/foo/bar/域的.默认的值是当前目录正在设置 cookie.

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.

相关文章