
There are quite a few ready-made counters - from liveinternet and to Yandex.Metrica and Google Analytics. All of them provide their users with the broadest functionality, but sometimes there are cases when you need the simplest traffic counter without using third-party services, for example, to display the number of page visits (as we have done, even in this post).
In this example, we'll show you how to create the simplest traffic counter. We will not record hundreds of parameters, as statistics services do, but save only the total number of visits. You can easily upgrade the counter, if necessary, to collect any information about your users and generate various kinds of reports.
To store information, we will use the file system, namely the file - counter.txt. It is not necessary to store information in a file, you can also use a database. The logic of the counter is quite simple: when a user requests a page, we open the file counter.txt, read the current number of visits and increase it by 1, then save the changes to our file.
In the code it looks like this:
<?php $count = 0; // по дефолту кол-во посещений будет равно нулю // Открываем наш файл для чтения, mode = r (read). Если ошибка – прекращаем дальнейшее выполнение. $file = fopen(“counter.txt”, “r”) or die("Can't read counter file – counter.txt"); // Считываем кол-во из открытого файла в переменную count while (!feof($file)) { $count = fgets($file); } // закрываем файл fclose($file); // выводим на экран кол-во посещений echo “Сайт посетило {$count} человек”; // увеличиваем старое кол-во на одно $count++; // открываем наш файл для записи mode = w (write) $file = fopen(“counter.txt”, “w”); // запишем изменения fwrite($file, $count); // закрываем файл fclose($file);?>
This script only works for one page. You can change it a little, for example, create your own file for each page, or use a database with a structure like:
id | counter
1 | 12
2 | 22