Hit Counter
This tutorial will show you how to create a way of tracking the unique visitor(s) to your site using Mimesis. NOTE: this is the actual code used on the main page of the Mimesis site.
STRUCTURE
This functions as a stand-alone script which you can cut and paste into an existing PHP page.
CODE
<?php
require_once('mimesis/Mimesis.php');
$cwd = realpath(dirname(__FILE__)); // The location where you want the table to be created (the directory where this script resides will suffice)
$tableName = 'hits'; // The name of the table
$rowLabel = str_replace('.', '_', $_SERVER['REMOTE_ADDR']); // The label for the row
$mimesis = new Mimesis($cwd, $tableName, 'ts_' . $tableName, 0644); // Instantiate Mimesis
if(!$mimesis->lock(1)){ // If the table doesn't lock display an error
echo 'HTTP/1.1 500 Internal Server Error';
}else{
if(!$mimesis->tableExists() || false === $mimesis->getRow($rowLabel, $rowLabel)){ // Check if row already exists
if(false === $mimesis->insertRow(array($rowLabel => array(null)))){ // If table fails to create display an error
echo 'HTTP/1.1 500 Internal Server Error';
}
if(!$mimesis->release()){ // Release lock on table
echo 'HTTP/1.1 500 Internal Server Error';
}
}
}
if($mimesis->tableExists()){
echo end($mimesis->entries()); // Display the number of entries which is equivalent to the number of hits
}
?>
KEY CONCEPTS
Some of the important things to keep in mind when viewing this code are the following:
- We use the IP address as provided by the $_SERVER['REMOTE_ADDR'] to create the row labels for our entries
- The entries we store are null arrays because we don't really care for any information other than the uniqueness of the IP address
- We test to see if an IP address already exists in our table by checking for its label
- To count the number of unique visitors we retrieve the number of unique rows in the table
- Permission 0644 are used in this example because on the 110mb.com server this corresponds to the most accessible php script permissions
- The lock performed here is a polling lock, which means it won't stop trying until it acquires a lock on the table OR the script times out
- We display errors in every possible location where one might occur