How to write a visitor counter in PHP.
<?php
$txt_file = "counter.txt";
if(file_exists($txt_file)) {
$f = fopen( $txt_file, 'r+' );
$count = fread($f, filesize($txt_file));
rewind($f);
$count++;
fwrite($f, $count);
ftruncate($f, ftell($f));
fclose( $f );
} else {
print "File Not Found";
}
$s = $count;
$line = sprintf("%s people have visited the site.", $s);
print $line;
?>
$txt_file = "counter.txt";
This variable is the text file.
if ( file_exists($txt_file) )
{
If the file is found continue, or print an Error.
$f = fopen( $txt_file, 'r+' );
Open the text file so we can read out the count value.
$count = fread( $f, filesize( $txt_file ) );
Read the text file, and fill the $count variable with the result.
rewind( $f );
Move the pointer to the beginning of the file
$count++;
Increment the $count value by "1".
fwrite( $f, $count );
Write the new number to the text file.
ftruncate( $f, ftell( $f ) );
Get rid of any extra space in the file that might exist from writing to it.
fclose( $f ); }
Close the text file, since we are finished with it.
else
{
print "File Not Found";
}
If the file was not found print an error.
$s = $count;
Move the $count variable to a new variable "$s".
$line = sprintf("%s people have visited the site.", $s);
Create a string that will print to the user, displaying the new $count number.
print $line;
Last but not least, we print the line back to the user.
That is the end of the counter tutorial. Now you should have a better understanding on it.