?php
session_start();
/**
* Counter class
* @version 0.1
* @author Monchovarela <nakome@gmail.com>
*/
class Counter{
/**
* Constructor
*/
public function __construct($file = ''){
$this->file = ($file) ? $file : 'counter.txt';
$this->val = '';
}
/**
* Make file
*/
public function makeFile(){
// Check if a text file exists. If not create one and initialize it to zero.
if (!file_exists($this->file)) {
$f = fopen($this->file, "w");
fwrite($f,"0");
fclose($f);
}
}
/**
* Get users
*/
public function getUsers(){
// Read the current value of our counter file
$f = fopen($this->file,"r");
$this->val = fread($f, filesize($this->file));
fclose($f);
}
/**
* Set users
*/
public function setUser(){
// Has visitor been counted in this session?
// If not, increase counter value by one
if(!array_key_exists('hasVisited', $_SESSION)){
$_SESSION['hasVisited']="yes";
$this->val++;
$f = fopen($this->file, "w");
fwrite($f, $this->val);
fclose($f);
}
}
/**
* Init class
*/
public function init(){
$this->makeFile();
$this->getUsers();
$this->setUser();
return $this->val;
}
}
$counter = new Counter();
$number = $counter->init();
echo "You are visitor number $number to this site";