Search code examples
phpcookiessetcookie

Cookie behavior seems to be 1 page delayed


I think I know the answer (I'm S.O.L.), but I thought I'd post the question anyway to see if anyone has any advice.

We have a website with cities on it. We're trying use cookies to 'remember' the current/last city the user has visited, but we're not getting the behavior we want. The cookie is always delayed 1 page (common pitfall listed here: http://php.net/manual/en/function.setcookie.php)

Let's say you go to the URL: site.com/dallas Then, you go to the URL: site.com/chicago

A cookie is set, before the < head > like this:

$location = 'Chicago';
setcookie("location", $cookie_loc, time()+31536000, "/"); 

The cookie is retrieved down on the page like this:

<?php
if(isset($_COOKIE["location"])) {
  echo 'Current City '.$_COOKIE["location"] ;
} else {
  echo 'Current City: none';
}
?>

However, on the 'Chicago' page, it is showing the 'Dallas' cookie that was set, even though the new cookie is set to 'Chicago'

Obviously, the cookie is being pulled down before it has been reset.

Is there a known way to correct this so that the cookie set by going to a page is also obtainable without refreshing the page?

My gut says no, but it's such a common issue I thought maybe...

Thanks!


Solution

  • If you set a cookie in a page, it won't be obviously available in that page. But if you set a location in that page, you can retrieve it from that variable!

    if (!isset($location) && isset($_COOKIE["location"]))
    {
        $location = $_COOKIE["location"];
    }
    
    echo 'Current City '. $location;
    

    If the $location variable isn't set at the beginning, then it gets retrieved from the cookies, otherwise the code uses that one. :)