Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

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.

Post History

66%
+2 −0
Q&A Load site based on cookie value in PHP

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 y...

posted 11mo ago by keyang‭

Answer
#1: Initial revision by user avatar keyang‭ · 2023-06-23T21:14:18Z (11 months ago)
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
    [...]