Creating a Counter with the GD library
In this example we will show how to create a counter which utilises the GD library to display the image . Why use the GD library you say , well this has a couple of advantages in that we can manipualte the size of the image , the color of the text , the color of the background and many other attributes as well .
First step is to create a new file called counter1.dat and enter the number you wish to start counting from . Now we will create the file which will create the actual image , remember you cannot have any html on this page , so cut and paste the code below and call this gdcount.php .
Code for gdcount.php
<?
Header("Content-type: image/jpeg");
//create an image
$image = imagecreate(100,40);
//create black color
$black = ImageColorAllocate($image, 0,0,0);
//create a white color
$white = ImageColorAllocate($image, 255,255,255);
//fill in background
ImageFilledRectangle($image ,0,0,100,40,$white);
//display our text
ImageString($image,5,15,20,$text,$black);
//render the image
ImageJPEG($image);
//destroy the image
ImageDestroy($image);
?>
Now for our actual counter , place this where you want the count to appear
Code
<?php
//simple counter example v1.0
//open the counter file in read only mode
$counterfile = "./counter1.dat";
if(!($fp = fopen($counterfile,"r"))) die ("cannot open counter file");
//read the value stored in the file
$thecount = (int) fread($fp, 20);
//close the file
fclose($fp);
//increment the count
$thecount++;
//display the count
echo "<img src =\"gdcount.php?text=$thecount\">";
//open the file again in write mode and store
// the new count
$fp = fopen($counterfile, "w");
fwrite($fp , $thecount);
//close the file
fclose($fp);
?>
Example :