Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Load site based on cookie value in PHP
I need to load a site based on a cookie. I wrote code to validate that, like this.
if(!isset($_COOKIE['cookie'])){
$domain = $_SERVER['SERVER_NAME'];
setcookie('cookie', $cookie, time() + 31536000, '/', $domain);
header('Location: '.$_SERVER['REQUEST_URI']); // reload
}
But when the cookie was created the first time I got this error:
1 answer
The problem is that you are using an undefined variable $cookie
. This will cause setcookie()
to "set" a cookie with name "cookie" and value null
. Obviously PHP deletes the cookie in that case, as you can observe with curl (also note the expiration time in the past):
curl $URL_OF_YOUR_WEBSITE -i
[...]
set-cookie: cookie=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/; domain=$YOURDOMAIN
[...]
Therefore, after the reload, the browser will not send the cookie (as it is expired = deleted), which brings us in the same situation as in the first request. Thus, the browser is running into an infinite loop of reloads.
(The same happens, by the way, if you set the cookie to value "".)
To fix the problem, set the cookie to a non-empty string, as in
if(!isset($_COOKIE['cookie'])){
$domain = $_SERVER['SERVER_NAME'];
setcookie('cookie', 'yes', time() + 31536000, '/', $domain);
header('Location: '.$_SERVER['REQUEST_URI']); // reload
}
Then, the cookie will actually be set (and not deleted) and the browser should be fine. With curl, you can see that the cookie is really set and has an expiration time in the future:
curl $URL_OF_YOUR_WEBSITE -i
[...]
set-cookie: cookie=yes; expires=Sat, 22-Jun-2024 21:02:32 GMT; Max-Age=31536000; path=/; domain=$YOUR_DOMAIN
[...]
1 comment thread