Simple Visits Counter without Database
Published on: 2005-08-14 - Views: 19416
In this tutorial we'll learn how to code a simple and basic visits counter.
This counter doesn't need any MySQL database, it runs using a simple txt file to be placed in it's same folder on the server.
First of all we have to create a txt file, our is named visits.txt. Open it and type "0" (only zero, without any quotation marks) in it, save and close the file. Move the file on your server, in the same folder where the script will be placed.
Now create a new PHP file and save it as simplecounter.php
<?php
$myfile = "visits.txt";
//we assign our file name to the variable we'll use to handle it
if(file_exists($myfile))//if the file exists
{
//we run our counter script $var = fopen( $myfile,\'r+\');
//opens in read and write mode our file
$visits = fread($var,filesize($myfile));
//puts the content of the file for its whole lenght
rewind( $var );
//resets the file position indicator to the beginning
$visits++; //increments the actual number of vists by 1
fwrite($var, $visits);
//writes in the variable the actual (incremented) value
fclose($var);//closes our file reference
}
else
{
print "File $myfile doesn\'t exist...";
Die();
//if the file doesn't exist prompts a warning and kills the script
}
$message = sprintf("%s visitors since 08/20/2005.",$visits);
//saves our visits message in a variable ($message) that will be used as output
print $message;
?>
You can use it in each page simply including it with a PHP include (see
our tutorial on PHP include) with the following syntax:
//we assign our file name to the variable we'll use to handle it
if(file_exists($myfile))//if the file exists
{
//we run our counter script $var = fopen( $myfile,\'r+\');
//opens in read and write mode our file
$visits = fread($var,filesize($myfile));
//puts the content of the file for its whole lenght
rewind( $var );
//resets the file position indicator to the beginning
$visits++; //increments the actual number of vists by 1
fwrite($var, $visits);
//writes in the variable the actual (incremented) value
fclose($var);//closes our file reference
}
else
{
print "File $myfile doesn\'t exist...";
Die();
//if the file doesn't exist prompts a warning and kills the script
}
$message = sprintf("%s visitors since 08/20/2005.",$visits);
//saves our visits message in a variable ($message) that will be used as output
print $message;
?>
<html>
<body>
<?php include 'simplecounter.php'; ?>
</body>
</html>
<body>
<?php include 'simplecounter.php'; ?>
</body>
</html>


