PHP cookie访问计数器无法正常工作

问题描述:

Hey I'm trying to make a counter of how many times someone is visiting my webpage and when it was the last time he visited. The last time visited is working fine. I'm having a problem to display how many times he has been on the page however. There's a bad display and it seems like I may be missing and incrementation somewhere but I can't seem to figure it out:

<?php
$Month = 3600 + time();

date_default_timezone_set('EST');
setcookie('AboutVisit', date("D M j G:i:s T Y"), $Month);
?>

 <?php
if(isset($_COOKIE['AboutVisit']))
{
$last = $_COOKIE['AboutVisit'];
echo "Welcome back! <br> You last visited on ". $last . "<br>";
 $cookie = ++$_COOKIE['AboutVisit'];


 echo ("You have viewed this page" . $cookie . "times.");
}
else
{
echo "It's your first time on the server!";
}
?>

EDIT: NEW CODE

<?php
$Month = 3600 + time();

date_default_timezone_set('EST');
setcookie('AboutVisit1', date("D M j G:i:s T Y"), $Month);
?>

 <?php
if(isset($_COOKIE['AboutVisit1']))
{
$last = $_COOKIE['AboutVisit1'];
echo "Welcome back! <br> You last visited on ". $last . "<br>";


}
if(isset($_COOKIE['visitCount1'])){


 $cookie = ++$_COOKIE['visitCount1'];


 echo ("You have viewed this page" . $cookie . "times.");
}
else
{
echo "It's your first time on the server!";
setcookie('visitCount1');
}
?>

You will need 2 cookies, one for the date and one for the counter.

Also remember that cookies must be sent before any other output is sent to the browser, or they will be lost (and an error generated), so it would be better to store your messages in variables and output them once you have completed ALL cookie processing.

It would also be simpler to save the time() in the date cookie and format its output only for viewing on the page.

<?php
if(isset($_COOKIE['LastVisitDate']))
{
    $msg1 = 'Welcome back! <br> You last visited on ' . date('d/m/Y H:i:s', $_COOKIE['LastVisitDate'])  . '<br>';
} else {
    $msg1 = "It's your first time on the server!";
}
setcookie('LastVisitDate', time(), time()+3600);   // reset to now

if ( isset($_COOKIE['VisitCount']) ) {
    $msg2 = "You have viewed this page {$_COOKIE['VisitCount']} times.";
    setcookie('VisitCount', (int)$_COOKIE['VisitCount']+1, time()+3600 );
} else {
    setcookie('VisitCount',1, time()+3600 );
    $msg2 = 'Thanks for visiting, I hope you enjoy your first visit';
}

echo $msg1;
echo $msg2;
?>

Also note that cookies can be blocked, by the browser, so this is not a completely reliable method of tracking users.

You forgot to call setcookie(). Take a look at http://www.w3schools.com/php/func_http_setcookie.asp

Try This

 <?php
if(isset($_COOKIE['AboutVisit']))
{
$last = $_COOKIE['AboutVisit'];
echo "Welcome back! <br> You last visited on ". $last . "<br>";
$value= $_COOKIE['AboutVisit']+1; //or whatever you wnt
setcookie("AboutVisit", $value);


 echo ("You have viewed this page" . $cookie . "times.");
}
else
{
echo "It's your first time on the server!";
}
?>