Object Oriented PHP Counter
Posted on December 21, 2007
Filed Under Access Counters |
A more advanced version of our PHP Counter, this script is object oriented and remembers return visitors by setting a cookie. Because it remembers visitors, this counter counts the number of unique visitors that visited your site.
This script is object oriented and written for PHP 5+, which handles object differently than older versions of PHP. Being object oriented allows multiple counters to exists on one page, or on different pages throughout the site. While you can copy this class into each page that you want to use it on, the best way is to include it in its own file at the top of your page. For example:
<?php
include(’counter_script.php’);
$myCounter=new Counter();
//NOW START HTML
?>
<html>
Because this script uses cookies, make sure to create the Counter object before you have any html or output! Cookies cannot be set if anything has been already output to the browser. To create the Counter object, call “$myCounter=new Counter()” after you have included the script. This creates a new Counter object, increments the counter, and sets a cookie letting the script know that the user has visited this site.
Here is the full script:
<?php
class Counter
{
//OBJECT INSTANCE VARIABLES
private $filename;
private $folder;
private $cookieName;
//USER CHANGEABLE DEFAULTS
//–REQUIRED
private $defaultFilename=’counter.txt’;
private $cookieExpireTime=86400; //ONE DAY, IN SECONDS
//–OPTIONAL
private $defaultFolder=”;
public function __construct($filename=”, $folder=”)
{
//CHECK FILENAME VARIABLE
if(empty($filename))
{
$this->filename=$this->defaultFilename;
}
else
{
$this->filename=$filename;
}
//CHECK FOLDER VARIABLE
if(empty($folder))
{
$this->folder=$this->defaultFolder;
}
else
{
$this->folder=$folder;
}
//CREATE COOKIE USING NAME OF FILE AND FOLDER
$this->cookieName=$this->filename.$this->folder;
//ONLY INCREMENT IF NEW VISITOR
if($this->isNewVisitor())
{
$this->checkFolder(); //CREATE FOLDER IF NEEDED
$this->increment(); //INCREMENT COUNTER
$this->setCookie();
}
}
private function checkFolder()
{
if(!empty($this->folder))
{
$this->createFolder($this->folder); //ATTEMPT TO CREATE FOLDER
}
else{} //NO FOLDER WANTED
}
private function createFolder($folder)
{
if(!is_dir($folder))
{
mkdir($folder, 0755); //IF DOESN’T EXIST, CREATE IT
}
}
public function isNewVisitor() //CHECK FOR COOKIE EXISTENCE
{
if(isset($_COOKIE[$this->cookieName])&&$_COOKIE[$this->cookieName]==true)
{
return false;
}
else
{
return true;
}
}
private function increment()
{
$this->currentCount=$this->getCount(); //GET COUNT USING OUR FUNCTION
$this->currentCount++; //INCREMENT
$this->setCount($this->currentCount); //SET COUNT
}
private function setCount($count)
{
if(!empty($this->folder)&&!empty($this->filename))
{
$this->writeToFile($count, $this->folder.’/’.$this->filename);
}
else if(!empty($this->filename))
{
$this->writeToFile($count, $this->filename);
}
}
public function getCount()
{
$contents=”;
if(!empty($this->folder)&&!empty($this->filename))
{
$contents=file_get_contents($this->folder.’/’.$this->filename);
}
else if(!empty($this->filename))
{
$contents=file_get_contents($this->filename);
}
if(is_numeric((int)$contents))
{
return (int)$contents;
}
return 0;
}
public function setCookie()
{
if(!setcookie($this->cookieName, true, time()+$this->cookieExpireTime))
{
echo “Error: Unable to set cookie, initialize this class before any html output on page is displayed.”;
}
}
private function writeToFile($msg, $path)
{
if(!$handle = fopen($path, “w”))
{
return false;
}
else
{
if(fwrite($handle, “$msg\r\n”) === FALSE)
{
return false;
}
}
fclose($handle);
return true;
}
}
?>
To display the value from the counter any time after you have created the counter object use the following code:
echo $myCounter->getCount();
This script is setup to be flexible as to how it stores the current count of visitors. By default, it creates a text filed called “counter.txt” in the same directory as the script and stores the count in there. You can also create the Counter() object with two arguments: Counter($filename, $folder) . This will allow you to choose the name of the file and the folder, if any, that it is contained in. By default, the file is not created in a folder. Here is an example:
<?php
include(’counter_script.php’);
$myCounter=new Counter(’myCounterFile.txt’, ‘counterFolder’);
//NOW START HTML
?>
<html>
If the folder does not exist, it will be created by the script.
Allowing these two arguments gives the developer some key functionality. Now, instead of just one counter file for the whole site, you can have a different counter for each page of your site. You could even have more than one counter on a page if you wanted. You could call your counter like the following example, and the counter file created would be the name of each page that the counter was on:
<?php
include(’counter_script.php’);
$currentPage=basename($_SERVER[’PHP_SELF’]);
$myCounter=new Counter($currentPage . ‘.txt’);
//NOW START HTML
?>
<html>
The counter file for this page would be “myPageName.php.txt” in this example.
Comments
Leave a Reply

