简体   繁体   中英

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;

$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;
// Sets counter to 0
$firstVisitcounter = 0;
$firstVisit = $_COOKIE['firstVisit'];
if ($firstVisitcounter == 0){
    // Counter is always 0 (set above)
    // so this will always run
    $firstVisitcounter = 1;
    setcookie('firstVisit', date("d-m-Y H:i:s"),  time()+3600);
}

You probably want to do something like

if (empty($_COOKIE['firstVisit'])) {
    // First visit...
} else {
    // Returning visitor
}

Every time the user accesses the page, $firstVisitcounter will be equal to 0.

Try doing:

if ($_COOKIE['firstVisit']=='') {

setcookie('firstVisit', date("d-m-Y H:i:s"),  time()+3600);

}

echo $_COOKIE['firstVisit'];

Instead of if ($_COOKIE['firstVisit']=='') , you can use:

(!isset($_COOKIE['firstVisit']) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM