Question

there!I write a piece of code to counter the vistor of my site with no refresh.the following is my code,can anyone give me some tips about the code and give some recommendation?

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

?>
Was it helpful?

Solution

you can use Google Analytics or a basic stats package. or you can track them through the ip addresses, where one person from one ip address is one visitor. or you can use cookies where you can set a cookie on visitor first request so you identify further request as coming from the same visitor

OTHER TIPS

You can serialize object on destruct by the magic method __destruct and make a static function that gives new instance of the unserialized one if exists :

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

Then call the file, if the temporal file exists, will recreate object and then sum counter :

~$ php counter.php
1
~$ php counter.php
2
~$ php counter.php
3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top