Hi everyone
I wrote small counter class. It counts number of daily visits. It remembers all ip addresses per page and counts them only once within any 24 hours per page and it works fine. Here is the code:
My question is what happens if I get 2 visits at the same time. They will get 2 identical instances of the class and obviously one visit will not be recorded. I know its not major issue but am just curious about possible solutions to this problem.
Thanx
I wrote small counter class. It counts number of daily visits. It remembers all ip addresses per page and counts them only once within any 24 hours per page and it works fine. Here is the code:
Code:
class Counter{
private static $instance;
public static $path = "Counter";
private $visits = array();
private $ip_reg = array();
private $current_date;
private function __constructor(){
$this -> $current_date = date("m.d.y");
}
public static function getFileInstance(){
if(file_exists(self::$path)){
self::$instance = (unserialize(file_get_contents(self::$path)));
}else{
self::$instance = new Counter();
}
return self::$instance;
}
private function saveFileInstance(){
file_put_contents(self::$path, serialize(self::$instance));
}
private function addVisit(){
if(isset($this -> visits[$_SERVER['PHP_SELF']])) {
$this -> visits[$_SERVER['PHP_SELF']] += 1;
}else{
$this -> visits[$_SERVER['PHP_SELF']] = 1;
}
}
private function register_ip(){
if($this -> current_date != date("m.d.y")){
$this -> ip_reg = array();
$this -> current_date = date("m.d.y");
}
$ip_adr = $_SERVER['REMOTE_ADDR'];
if($this -> ip_reg[$ip_adr][$_SERVER['PHP_SELF']] != 1){
$this -> ip_reg[$ip_adr][$_SERVER['PHP_SELF']] = 1;
$this -> addVisit();
$this -> saveFileInstance();
}
$this -> printCounter();
}
private function printCounter(){
echo $this -> visits[$_SERVER['PHP_SELF']];
}
public function run(){
$this -> register_ip();
}
}
Thanx
Comment