To make our text file counter we are going to make use of two files: counter.php and count.txt. The following is the code for the counter.php file. For it to work properly you will need to upload a count.txt file to your server previously and chmod it to 666. The text file must contain the number 1. Each time you refresh the counter.php page the count will increase in 1.
|
<?php
$file = fopen( "count.txt", 'r' );
while ( ! feof( $file ) )
{
$count = fgets( $file );
}
$count++;
print $count;
fclose( $file );
$file = fopen( "count.txt", "w" );
fwrite( $file, $count );
fclose( $file );
?> |
Now lets explain the code above. To open a file for reading you need to use the fopen function and give it two arguments, the file name (count.txt), and the 'r' that represents that the file is being opened for reading. If you want to open a file for writing then you use 'w' and for append 'a'.
Now the next code chunk.
while ( ! feof( $file ) )
{
$count = fgets( $file);
}
This actually reads the file. It means that while our file has not reached the end of file ( ! feof) it should read the next line. To read a line you make use of the fgets function. It requires the name of the file been read ($file)
$count++;
print $count;
fclose( $file );
With the above we add 1 number to the count, print it and then close the file.
$file = fopen( "count.txt", "w" );
fwrite( $file, $count );
fclose( $file );
The above code open the file now for writting purposes. The second line uses the fwrite function to write to our count.txt file. This function needs the name of the file to be use ($file) and the value to enter it. In this case it was a variable but it also can be a string. Finally, to keep everything clean, we close the file.