CodeLair scripts and tutorials; click to return to home page

PHP Hit Counter

This script will allow you to track the number of (non-unique) visitors to your site, or to each page.
Last updated: July 17, 2007

The first script will show you how to put a very simple hit counter on your pages. When a visitor loads the page, the count (stored in a file) is incremented. You can also choose whether or not to display the hit count on your pages.

The second script below is similar to the first, however this one keeps track of the number of hits to each page separately and displays the hit counts in order of popularity. It is available for quick download if you don't wish to learn how it works.

 

The basic script

View Demo

Create a blank text file called hitcount.txt. This will be used to store the number of hits on a page, or across all pages. Upload this, and CHMOD it to '666' (there should be an option in your FTP program to do this - consult the Help files if you are not sure).

In a text editor, create a file named counter.php. Copy the following code into it:

<?php

$filename = 'hitcount.txt';
$handle = fopen($filename, 'r');
$hits = trim(fgets($handle)) + 1;
fclose($handle);

$handle = fopen($filename, 'w');
fwrite($handle, $hits);
fclose($handle);

// Uncomment the next line (remove //) to display the number of hits on your page.
//echo $hits;

?>

The first section opens the file in reading mode. It reads the number of hits in the file, which is then incremented and written back to the file. Every time counter.php is opened the number of hits goes up. So on every page you want to record the number of visitors, you need to include counter.php by means of a PHP include:

<?php include("counter.php"); ?>

As per usual, change counter.php to your path to the file. If you include it on every page of your site, you will count the total number of hits for all your pages (note that this is not unique visitors), and if you just put it on one page (say, the home page), you will count the number of hits for that page only.

You can also use the counter on SHTML pages (with .shtml extension), provided that your server supports PHP (and SSI of course). Just use this include:

<!-- #include file="counter.php" -->

Do you want to display the number of hits on your page somewhere? Simply uncomment the last line by removing the double slash so it reads:

echo $hits;

Then include the script wherever you want the count to be displayed. Since the script just displays a number, you can wrap the include in any HTML you want, for example:

<p>This web site has had <b><?php include("counter.php"); ?></b> hits since January 1st, 2007.</p>

 

A more advanced script

What if you want to track the number of hits to each page individually? With the previous script you'd have to make separate counter.php and hitcount.txt files for every page you wanted to track. With the following script, this is not necessary: we have one PHP file which recognizes the current page being viewed and tallies a hit for that page. The text file now stores the page URL and the number of hits for that page. A new page, viewhits.php, displays all the pages and their respective hit counts. You can download the whole set of files in one zip file at the bottom of the page.

View Demo

View the hit list

First create a new blank hitcount.txt file (perhaps in another folder), and then copy this code into a new counter.php file:

<?php

$filename = 'hitcount.txt';
$handle = fopen($filename, 'r');
$outbuffer = '';
$found = false;
$hits = 1;

// reading data from file
while ( !feof( $handle ) )
{
  $buffer = trim( fgets( $handle ) );
  if ( strlen( $buffer ) > 0 )
  {
    list( $page, $count ) = explode( '|', $buffer );
    if ( !$found && $page == $_SERVER[PHP_SELF] )
    {
      $hits = $count + 1;
      $outbuffer .= $_SERVER[PHP_SELF] . '|' . $hits . "\n";
      $found = true;
    }
    else
    {
      $outbuffer .= $buffer . "\n";
    }
  }
}
fclose($handle);

if (!$found)
{
  $outbuffer .= $_SERVER[PHP_SELF] . "|1\n";
}

// writing updated data to file
$handle = fopen($filename, 'w');
fwrite($handle, $outbuffer);
fclose($handle);

// Uncomment the next line (remove //) to display the number of hits on your page.
//echo $hits;

?>

As before, include this file on any page you want to count hits for. With the last line of code uncommented, the number of hits for the visited page will be displayed.

 

Viewing stats for all your pages

Finally, make another new PHP file, called viewhits.php. This first bit of code reads the list of pages and hit counts from the text file, and sorts the list based on the number of hits (descending). The total number of hits for all pages is also counted.

<?php

$filename = "hitcount.txt";
$i = 0;

// get list of pages from file
$handle = fopen($filename, 'r');
while ( !feof( $handle ) )
{
  $buffer = trim( fgets( $handle ) );
  if ( strlen( $buffer ) > 0 )
  {
    list( $pages[$i], $count[$i] ) = explode( '|', $buffer );
    $total += $count[$i];
    $i++;
  }
}
fclose($handle);

// sort list
array_multisort($count,SORT_DESC,$pages);

The second part displays the results in a nice table. To see the styled table you will need to download the zip file below, which has the stylesheet and image.

The numbers are formatted, using the PHP function number_format. This makes large numbers easier to read by adding commas in the standard way, e.g. '1,234' or '9,876,543'.

echo '<h1>CodeLair Hit Counter</h1>';
echo '<p class="info">TOTAL HITS<br /><b>' . number_format( $total ) . '</b></p>';

echo '<table>';
echo '<tr><th>Filename</th><th>Hits</th></tr>';

for ( $j = 0; $j < $i; $j++ )
{
  echo '<tr>';
  echo '<td class="text">' . $pages[$j] . '</td>';
  echo '<td class="number">' . number_format( $count[$j] ) . '</td>';
  echo '</tr>';
}
echo '</table>';
echo '<p class="info">PHP hit counter script by <a href="http://www.doheth.co.uk/codelair">CodeLair PHP scripts</a></p>';

?>

 

Script download

You can now download the advanced script in a zip archive. Simply unzip, upload all the files to your web space, CHMOD the text file to '666', then use the include on each of your pages.

Download script
VERSION 2.0 (rewritten from scratch)