Search code examples
phpsetcookie

PHP - Cookie can't be read after the page is refreshed


I know this is a common question, but nothing seems to be working. I have created an age gate to a site and if the user fails they should no longer have access to try again for 30 days and it will just display a "denied" message. If they succeed, they will then be shown the content.

Note: This all happens on a single page/file and after submission, the age is checked and the appropriate cookie is set, then the page is refreshed to display the corresponding content.

I am setting it like this:

if($year > 0  && $month > 0 && $day > 0){
    if (time() < strtotime('+18 years', strtotime($submittedDate))) {
        setcookie('age_check', 'denied', time() + (86400 * 30), '/', '.domain.com');
        header('Refresh:0; url=/subpage');
    }else{
        setcookie('age_check', 'validated', time() + (86400 * 30), '/', '.domain.com');
        header('Refresh:0; url=/subpage');
    }
}

Then I check using this:

if($_COOKIE['age_check'] == 'denied'){
    echo '<h1 class="age-error">Sorry, you may not access this content.</h1>';
    return;
}elseif(!isset($_COOKIE['age_check'])){
    // if it's not present at all, display the age form
}else{
    // it must be set and validated, so show the age gated content
}

Just before it refreshes, I am outputting the cookie value for testing and see it output for a split second, but after it refreshes it's empty and just displays the form without any error message or displaying the content, which tells me that !isset($_COOKIE['age_check']) is returning true. However, I can see it set in dev tools and it has the correct value.

Can someone please explain what's going on here?


Solution

  • So in case anyone else is having this weird issue, I found the answer.

    Seems specific to WP Engine (possibly other hosts as well) and the way that they cache cookies on their end. So I had to contact them and have them add the specific cookie name to an exclusion list under the cache settings. They don't allow you to do this yourself, so you have to contact them to get it added, but at least it was a quick chat.