Article content

Simple PHP counter without database access

Tagged in php, counter, analytics, phphowto

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

  1. <?php
  2. $countfile='counter.txt';
  3. $fh = fopen($countfile, r);
  4. $dat = @fread($fh, filesize($countfile));
  5. fclose($fh);
  6. $fh = fopen($countfile, "w");
  7. fwrite($fh, intval($dat)+1);
  8. fclose($fh);
  9. ?>

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:

  1. <?php
  2. $countfile='counter.txt';
  3. readfile($countfile)
  4. ?>

Simple as cake. For your convenience, here is a zipped archive with the three files you need.

simplecounter.zip (1.85Kb)

Discussion

Submit your comment

Text:

Your name:

Your email:

Show my mailaddress (spam protected)

Your website:

Show my website

Featured Article

PHP Variables and strings

A variable is a means of storing a value, such as a text string or a number. In PHP you do not have to declare your variable, as it's automatically declared when you set it. Since you do not need to declare the variable, you do not have to specify what kind of data it contains either.

Topics
Magicode's own open source project
From the forum / Latest comments
You may also want to to check out these links: sendanonmail.com, superstrongpassword.com.