How to create a simple counter or visitor counter with PHP and text file?

Vitali Lutz
226 Words
57 Seconds
179
0

With PHP it is very easy to create a counter or a visitor counter. We can use all internal functions of PHP for this.

First we have to count all calls of the script and save them in a text file. We also make sure that each visitor/call is counted only once, for which we use the cookie function of PHP. Finally, we can output the current count everywhere using the file_get_contents function.

Here is the finished PHP script:

<?php

$document_root = $_SERVER['DOCUMENT_ROOT'];

// Load counter from file
if (file_exists($document_root . '/counter.txt')) {
  $counter = file_get_contents($document_root . '/counter.txt');
} else {
  $counter = 0;
}
$counter += 1;

// Increase counter for unique calls
if (!isset($_COOKIE['counter'])) {
  file_put_contents($document_root . '/counter.txt', $counter);
  setcookie('counter', '1', (time() + 86400));
}

// Output counter
echo file_get_contents($document_root . '/counter.txt');

The big advantage of the counter is that no database is needed. We store everything in a simple text file located in the main directory of the website. Moreover, all the logic can be packed into a function and you can create counters with any name.

If you want to reset the counter, just remove the file "counter.txt" and the script will start counting the calls from the beginning. Note that you must inform visitors that you are setting cookies and what they are used for, as required by the Privacy Policy.

Vitali Lutz

About Vitali Lutz

Vitali Lutz is a versatile author on all aspects of business and technology. Thanks to his ability to adapt to a wide range of topics and his great thirst for knowledge, he writes about anything that interests him.

Redirection running... 5

You are redirected to the target page, please wait.