PHP cookie 访问计数器不工作

PHP cookie visit counter not working

嘿,我正在尝试计算某人访问我的网页的次数以及他最后一次访问的时间。最后一次访问工作正常。 然而,我在显示他在页面上的次数时遇到了问题。 显示效果不佳,似乎我可能在某处丢失和增加了,但我似乎无法弄清楚:

<?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!";
}
?>

编辑:新代码

<?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');
}
?>

您忘记打电话给 setcookie()。看看http://www.w3schools.com/php/func_http_setcookie.asp

试试这个

 <?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!";
}
?>

您将需要 2 个 cookie,一个用于日期,一个用于柜台。

另外请记住,cookie 必须在任何其他输出发送到浏览器之前发送,否则它们将会丢失(并产生错误),因此最好将您的消息存储在变量中并在您发送后输出它们已完成所有 cookie 处理。

time() 保存在日期 cookie 中并将其输出格式化为仅供在页面上查看也会更简单。

<?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.