|
This simple tutorial will explain how to program a simple text-file counter. Creating a simple counter requires you do three things:
Open up a file and read current count value.
Add one to the current value.
Read and print the new value.
So for the this tutorial, first create a file called sample.php and put a 0 in it as a default start point.
Now the actual code for the counter:
<?php
//tutorial for text-file based counter
$counthandle=fopen("sample.php","r");
//opens file for reading and writing
$getcurrent=fread($counthandle,filesize("sample.php"));
//reads in current value
$getcurrent=$getcurrent+1;
//increment count by 1
fclose($counthandle);
$counthandle1=fopen("sample.php","w");
fputs($counthandle1,$getcurrent);
//input new value
fclose($counthandle1);
$counthandle2=fopen("sample.php","r");
$getrecent=fread($counthandle2,filesize("sample.php"));
//gets new value
print "$getrecent";
//print counter value
fclose($counthandle2);
?>
The comments are provided below each line tell what the line above does.
First the "$counthandle" variable opens up your sample.php file which you created for reading.
The freads function reads whatever is in sample.php and stores it in $getcurrent. fclose() closes file handles.
The $counthandle1 opens up the sample.php file for writing. We already incremented $getcurrent by one before hand so now we use fputs to
write the new value over the old value we had. Finally, $counthandle2 opens the new sample.php and reads the new file and stores it in the
$getrecent variables. The last line simple prints whatever is in $getrecent.
A example is provided below:
This tutorial has been viewed 4224 times.
|