PHP cookie访问计数器不工作 [英] PHP cookie visit counter not working

查看:112
本文介绍了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!";
}
?>

编辑:新代码

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


推荐答案

您需要2个Cookie,

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

还要记住,cookies必须在任何其他输出发送到浏览器之前发送,否则它们将丢失(并生成错误),因此,

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




另请注意,浏览器可能会阻止Cookie,因此不是一个完全可靠的跟踪用户的方法。

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

这篇关于PHP cookie访问计数器不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆