student.ccbcmd.edu It's yours, use it!

Creating a Simple Web Site Counter

This tutorial will help you place a simple text file counter for your student web page. Something like this...

You are visitor 499.

Step 1: Creating the Text File

First you must create a text file on the server to store the total number of hits to your page. This files permissions will need to be changed to read/write. This way you are able to read in the total number of hits and also write a new value to the file when someone visits the page.

Step 2: The php Code

Now that you have a text file to track your hits you need to actually track your hits! The concept behind this code is to read the value in the mycounter file add 1 and then write the value back into the file. It's a very simple procedure.

The code below needs to be pasted on the page you would like to place the counter.

<?php
// path and file name to mycounter.txt
$filename = "mycounter.txt";

// Open the file to read the current value
$readme = fopen($filename, "r");

// Read the value and place it in the variable called $counterval
$counterval = fread($readme, filesize($filename));

// Close the file
fclose($readme);

// Increment the counter by adding one to $counterval
$counterval = $counterval + 1;

// Open the file to write the new value
$writeme = fopen($filename, "w");

// Write the new value of counter to the file.
fwrite($writeme, $counterval);

// Close the text file.
fclose($writeme);

// Display $counterval
echo "You are visitor $counterval.";
?>

Learn more about the functions this counter code uses by click on the function below:

Step 3: Customizing the look of the counter

If you looked at the previous code or even implemented it you probably realized the line in the code that actually writes the counter to the screen is...

echo "You are visitor $counterval.";

You can change this text to read anything you like, as long at $counterval stays intact. $counterval is the variable that holds the counter value. You can even add html formatting take to change the look or apply a CSS class. For example...

echo "<b>You are visitor $counterval.</b>";

or

echo "<span class=\"counter\">You are visitor $counterval.</span>";

Here is a formatted counter using the above span example and a style defined in an external style sheet.

499

Things to think about!

  1. How valuable is the above counter? Is the data you get accurate?
  2. Is there a way to track unique hits?
  3. What if I used a database table instead of a text file?
  4. What happens if I place this code on more then one page?