How to make a Visitor Counter using PHP

Post Reply
Tony
Lieutenant
Lieutenant
Posts: 86
Joined: Tue Jul 21, 2009 4:11 pm

How to make a Visitor Counter using PHP

Post by Tony » Sun Nov 29, 2009 4:04 am

This simple script creates an image that can be used on any page to display a visitor counter. A session variable is used to ensure that the counter only advances once per browser session (the most accurate way to count website visitors).

In your html, put an <img> tag for the image, such as the one below. Do not put width or height parameters in the img tag as this will distort the generated image.

Code: Select all

<img src="counter.php" alt="counter" style="border: inset 3px;"> 
Name the script below counter.php.

You can download this script as a .txt file. Remember to rename the file as a .php file.

Code: Select all

<?php
$filename = 'counter.dat';
session_start();
if (!isset($_SESSION['visitor_counter']) AND is_writable($filename)) {
  $count = @file_get_contents($filename);
  if (is_numeric($count)) {
    $count++;
    @file_put_contents($filename,$count,LOCK_EX);
    $_SESSION['visitor_counter'] = $count;
  }
} else {
  $count = $_SESSION['visitor_counter'];
}
$width = (strlen($count)*8)+8;
$im = @imagecreate($width, 18);
$background_color = imagecolorallocate($im,255,255,255);
$text_color = imagecolorallocate($im,0,0,0);
imagestring($im,4,4,2,$count,$text_color);
imagepng($im);
imagedestroy($im);
?> 
The count value is stored in a file counter.dat. Create a starter counter.dat file with notepad with a good starting value (say 50 - give yourself a few starter hits). You can cheat any time just by changing the value in counter.dat with notepad.

Put your web page, counter.php and counter.dat in the same directory.

If you want an invisible counter (cannot be seen on the page), you can simply use the following <img> tag in the html page:

Code: Select all

<img src="counter.php" alt="" style="display: none;">  

If you would like a comma in the number if the number is more than 3 digits, then add this line just before the $width calculation:

Code: Select all

if (strlen($count)>3) $count = substr($count,0,strlen($count)-3).",".substr($count,strlen($count)-3,3);  

If you are using a PHP page and want to include the counter in a text line rather than display it as an image, as is done at the bottom of this page, you can simply replace the bottom half of the script (everything after the if/else test) with this one line:

Code: Select all

echo "You are visitor $count";  
Do not use the <img> tag, but rather use a php include('counter.php'); where you want the counter on your page.


Note - If the user's browser is blocking cookies, then the counter will count each page hit rather than browser sessions.
Post Reply

Return to “PHP & MySQL”