dr897777 2013-06-21 15:27
浏览 31

php每日计数器多次访问bug

I'm writing , just to experiment , a web page daily hit counter using PHP.

Multiple access from the same browser during the same day should be counted as 1, in order to do that I'm using cookies.

The problem is that , before the browser gets the cookie , the script can be executed in parallel multiple times without any thread finding the cookie , therefore the counter does not work as expected.

So how can I avoid the script is executed in parallel to serve requests coming from the same browser ?

thanks.

Here's the example: note that to make debugging easier the day is now 1 minute long :D,
the counter is the second value from the left.
http://ralfralf.atwebpages.com/index2.php

here's the code: (can someone help me making it look readeable?) :D

<?php

$visitsfile = file("visits.txt");

if( ! isset($_COOKIE["visitor"] ) )
  {
    $rest = time() % 60;
    $rest1 = 60 - $rest;
    setcookie("visitor" , "visitor" , time() + $rest1 );

    $bolval = 0;

    if( sizeof($visitsfile) > 0)
      {
        $i = sizeof($visitsfile) - 2;

        $val = floor( ( intval( substr( $visitsfile[$i] , 0 , - 1) ) / 60 ) ) - floor( ( time() / 60 ) ) ;

        if(  $val == 0 )
          {
            $visitsfile[$i+1] = intval( substr( $visitsfile[$i + 1] , 0 , - 1) ) + 1 . "
";
            $bolval = 1;
          }
      }       

    if( sizeof($visitsfile) == 0 || !$bolval)
      {
        if(sizeof($visitsfile) == 0)
          {
            $i = 0;
          }
        else
          {
            $i = sizeof($visitsfile);
          }

        $visitsfile[$i] = time() . "
";
        $visitsfile[$i+1] = "1
";
      }

    $fp = fopen("visits.txt", "w");

    if (flock($fp, LOCK_EX))
      {
        $i = 0;
        while($i < sizeof($visitsfile))
          {
            fwrite($fp, $visitsfile[$i] );
            $i++;
          }
        flock($fp, LOCK_UN);
      }
    fclose($fp);
  }

$n = sizeof($visitsfile);

if(! isset($_COOKIE["visitor"]))
  {
    echo intval( substr( $visitsfile[$n - 2] , 0 , - 1) ) . " " . (intval( substr( $visitsfile[$n - 1] , 0 , - 1) ) - 1 ) ;
  }
else
  {
    echo intval( substr( $visitsfile[$n - 2] , 0 , - 1) ) . " " . intval( substr( $visitsfile[$n - 1] , 0 , - 1) ) ;
  }


?>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 基于卷积神经网络的声纹识别
    • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
    • ¥100 为什么这个恒流源电路不能恒流?
    • ¥15 有偿求跨组件数据流路径图
    • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
    • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
    • ¥15 CSAPPattacklab
    • ¥15 一直显示正在等待HID—ISP
    • ¥15 Python turtle 画图
    • ¥15 stm32开发clion时遇到的编译问题