首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >php计数器避免刷新

php计数器避免刷新
EN

Stack Overflow用户
提问于 2014-02-20 15:07:22
回答 2查看 100关注 0票数 0

在那里!我写了一段代码来对抗我的站点的访问者,没有refresh.the,下面是我的代码,有人能给我一些关于代码的提示和一些建议吗?

代码语言:javascript
复制
<?php

    $counterFile='counter.txt';
    $ipFile='ip.txt';
    if(!is_file($counterFile)){
        file_put_contents($counterFile,0);
    }
    if(!is_file($ipFile)){
        file_put_contents($ipFile,0);
    }


    $handle=fopen($counterFile,'rb') or die('error:can not open the counter file');
    $fileSize=filesize($counterFile);
    $counter=intval(fread($handle,$fileSize));
    fclose($handle);
    /**----$counter=file_get_contents($counterFile);----***/

    $oldIp=file_get_contents($ipFile);
    $currIp=$_SERVER['REMOTE_ADDR'];
    //echo $oldIp.'==='.$currIp;


    if($oldIp!=$currIp){
        ++$counter;
        $handle=fopen($counterFile,'wb');
        fwrite($handle,$counter);
        fclose($handle);
        /**----file_put_contents($counterFile,$counter);----***/
    }


    file_put_contents($ipFile,$currIp);


    echo $counter;

?>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-02-20 15:13:37

您可以使用或基本的统计软件包。或者您可以通过ip地址跟踪它们,其中一个ip地址中的一个人是一个访问者。或者您可以使用cookie,在此您可以根据访问者的第一次请求设置cookie,这样您就可以识别来自同一个访问者的进一步请求。

票数 0
EN

Stack Overflow用户

发布于 2014-02-20 15:20:45

您可以通过魔术方法毁伤在析构上序列化对象,并创建一个静态函数,如果存在,该静态函数将提供未序列化对象的新实例:

代码语言:javascript
复制
<?php

class Counter {
   const CACHE_FILE = '/tmp/counter.clss';
   protected $_counter = 0;
   public function up(){
     $this->_counter++;
   }

   public function down(){
     $this->_counter--;
   }

   public function howmany(){
     print $this->_counter;
   }

   public function __destruct(){
     file_put_contents(self::CACHE_FILE,serialize($this));
   }

   public static function retrieve(){
     if(file_exists(self::CACHE_FILE)){
       $obj = unserialize(file_get_contents(self::CACHE_FILE));
     }else{
       $obj = new self;
     }
     return $obj;
   }
}
$ctr = Counter::retrieve();
$ctr->up();
$ctr->howmany();

然后调用该文件,如果存在时态文件,将重新创建对象,然后求和计数器:

代码语言:javascript
复制
~$ php counter.php
1
~$ php counter.php
2
~$ php counter.php
3
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21911687

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档