問題描述
經過一些處理后,我想為用戶輸入設置一個 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.
這篇關于如何設置 cookie 然后在 PHP 中重定向?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!