The Simple Counter Implementation in PHP

Posted on Posted in code, implementation, php

The following is a simple counter implementation that is based on PHP, if you have a small site of low traffic, or you just want to have a very simple counter implemented in your page, and that does not need to be highly accurate.

It works by reading the value from the counter text file (instead of MySQL database), increment the value by one, and store it back. However, if you have quite a lot of visitors accessing the page at the same time, triggering the I/O, some threads may skip the counting.

1
2
3
4
5
6
7
8
9
10
function SimpleCounter($file = "SimpleCounter.txt") {
        if (!is_file($file)) {
                file_put_contents($file, 0);
                return 0;
        }
        $value = file_get_contents($file);
        $value ++;
        file_put_contents($file, $value, LOCK_EX); // LOCK the file
        return $value;
}

Use this like:

1
echo "Page Views: " . SimpleCounter();

If you really want that to be accurate, use the MySQL instead, but the above provides you a quick-and-dirty implementation, which should be good enough if you just need a simple counter!

–EOF (The Ultimate Computing & Technology Blog) —