Image hit counter in PHP

To create an image counter we will firstly create a file that will keep the counter.

$txtFile = 'counter.txt';
$number = (string) (((int) file_get_contents($txtFile)) + 1);
$open = fopen($txtFile,'w');
fwrite($open, $number);

The file counter.txt will hold the counts. The contents of the file are converted into an integer and the value is incremented. This value is then converted to a string and stored back in the file. It was converted into a string so that we can get each digit separately so that we can load an image for each digit.

for($i=0; $i < strlen($number); $i++)
   echo '<img src="count'.$number[$i].'.png" alt="'.$number[$i].'" />';

Now that we have the counter value we loop over the digits and output the corresponding digits.

The characters in a string can be accessed like an array, hence string[0] is the first character in the string.

This technique can also be used with the counter in a database.

mysql_connect('localhost','root','root'); mysql_select_db('test2');
$result = mysql_fetch_array(mysql_query("SELECT * FROM counter WHERE id='1'"));
$number = ($result['counter']) + 1;
$result = mysql_query("UPDATE counter SET counter = '$number' WHERE id='1'");
$number = (string) $number;

The counter value is returned from the database and is incremented and the database is updated. Again the number is converted into a string so that it can easily be looped over to output the correct images.