Search code examples
phpcookiessetcookie

setcookie keeps updating, PHP


So this is my code. Both my husband and I have looked at it and we do not understand why the date and time keeps updating. The first time the if statement is run it should work, but then it should stop. But it doesn't. How do I get the time to stop and just display as it was instead of updating?

$firstVisitcounter = 0;
$firstVisit = $_COOKIE['firstVisit'];
if ($firstVisitcounter == 0){
    $firstVisitcounter = 1;
setcookie('firstVisit', date("d-m-Y H:i:s"),  time()+3600);
}

echo $firstVisit;

Solution

  • $firstVisitcounter = 0; is the first line, so the if will always execute. You might just want to check for the cookie:

    if(isset($_COOKIE['firstVisit'])) {
        $firstVisit = $_COOKIE['firstVisit'];
    } else {
        $firstVisit = date("d-m-Y H:i:s");
        setcookie('firstVisit', $firstVisit,  time()+3600);
    }
    
    echo $firstVisit;