Simple PHP counter without database access
Every web site needs a counter. You can implement Google Analytics or some other fully fledged statistics system, but for most sites, that's just overkill. Read on for a simple PHP-based counter that does not rely on database access.
Three files is all you need, two PHP-scripts and a text file to store the current count. Here's how to do it. Permalink for this article http://mirror.magicode.org/content/Simple_PHP_counter_without_database_access
The script: This text was originally written for http://blog.magicode.org
- <?php
- $countfile='counter.txt';
- $fh = fopen($countfile, r);
- $dat = @fread($fh, filesize($countfile));
- fclose($fh);
- $fh = fopen($countfile, "w");
- fwrite($fh, intval($dat)+1);
- fclose($fh);
- ?>
This script will open a local file called counter.txt, read the contents and put it in the variable called $dat. Further, it will close the file, then reopen it and write the new count, which is the current number plus one. If you see this notice on any site other than magicode.org, it's probably been lifted without consent
The counter.txt will need to be created first, and you may need chmod it so that it is writable by www.
For reading the counter, a simple call to readfile will do the trick. Here's what you do:
- <?php
- $countfile='counter.txt';
- readfile($countfile)
- ?>
Simple as cake. For your convenience, here is a zipped archive with the three files you need.
simplecounter.zip (1.85Kb)
