Cookie页面计数器在PHP [英] Cookie page counter in php

查看:128
本文介绍了Cookie页面计数器在PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实施一个PHP页面计数器,它将跟踪用户每次访问此页面时,直到浏览器关闭。我检查看是否设置了cookie,如果是的话。然后我增加它并重置其值。但我遇到的问题是,计数器总是在两个,为什么是这样?

I am implementing a php page counter that will keep track of each time the user visits this page until the browser is closed. I am checking to see if the cookie is set, if it is. Then I am increment it and reset its value. But the problem I am having is that the counter is always at two, why is this?

<html> 
    <head> 
        <title>Count Page Access</title> 
   </head> 
  <body> 
<?php 

    if (!isset($_COOKIE['count']))
    {
        ?> 
Welcome! This is the first time you have viewed this page. 
<?php 
        $cookie = 1;
        setcookie("count", $cookie);
    }
    else
    {
        $cookie = $_COOKIE['count']++;
        setcookie("count", $cookie);
        ?> 
You have viewed this page <?= $_COOKIE['count'] ?> times. 
<?php  }// end else  ?> 
   </body> 
</html>

编辑:感谢大家,我做了增量递增的事情, strong>

Thanks everyone, I did the pre increment thing and got it to work

推荐答案

这是因为 ++ 作为后递增而不是预递增。基本上发生的是你在说,将 $ cookie 设置为 $ _ COOKIE ['count']的值,然后增加 $ _ COOKIE ['count'] 。这意味着每次你设置它只是 $ cookie 等于1,即使 $ _ COOKIE ['count'] 显示为2,您发送的实际Cookie只会等于1。 $ cookie = ++ $ _ COOKIE ['count']; 您应该得到正确的结果。

This is happening because of the ++ being used as a post-increment instead of a pre-increment. Essentially what is happening is you're saying, "set $cookie to the value of $_COOKIE['count'], and then increment $_COOKIE['count']. This means that each time you set it you're only actually making $cookie equal 1, and even though $_COOKIE['count'] is showing it as 2, the actual cookie you send will only equal 1. If you do $cookie = ++$_COOKIE['count']; you should get the correct result.

这篇关于Cookie页面计数器在PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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