// phpShack / PHP & MySQL Tutorials / Simple PHP Counter
 

Navigation





 

Simple PHP Counter

The focus of this tutorial is to show you how to make a very simple PHP hit counter. The main drawback of this counter is that it counts pageviews not unique hits. I will show you how to create a more advanced hit counter later.

So lets get started:
First off we are going to work on the guts of the script, we will call it counter.php (who would have guessed)


PHP Code Example:
<?
// counter.php
/* First we assign a variable name to our 
   txt file that holds our number of hits. */
$count_file = ("counter.txt");
/* This next line sets the variable $number_of_hits equal 
   to the value inside the counter.txt */
$number_of_hits file($count_file);
/* Now our next line will increment the number of 
   hits in the counter.txt by 1, this will happen 
   everytime the page loads. */
$number_of_hits[0]++;
/* Next we need to open the counter.txt file so we 
   can write to it, the "w" gives us write priviliges. */
$fp fopen($count_file "w");
/* Now we instert the new counter value after we added 
   1 to it into the counter.txt file */
fputs($fp "$number_of_hits[0]");
/* Now we close our connection to counter.txt */
fclose($fp);
/* And last but not least we print the new counter 
   value to the screen using the echo command. */
echo $number_of_hits[0]; 
?>

Now to use this counter you have 2 options. One you can just enter this code into the place you want the counter. Two you can this code in the page where you want the counter.
<?
include "counter.php";
?>