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
2), Opera (12.11) both on Windows and Mac, set cookies on redirects. This is true for both 301 and 302 redirects. The SameSite attribute of a cookie specifies whether the cookie should be restricted to a first-party or same-site context.
Answer: Use the PHP header() Function You can simply use the PHP header() function to redirect a user to a different page. The PHP code in the following example will redirect the user from the page in which it is placed to the URL http://www.example.com/another-page.php . You can also specify relative URLs.
The setcookie() function defines a cookie to be sent along with the rest of the HTTP headers. A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too.
In PHP, when you want to redirect a user from one page to another page, you need to use the header() function. The header function allows you to send a raw HTTP location header, which performs the actual redirection as we discussed in the previous section.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With