Pageview Counter in PHP

Take a trip back to the '90s and add a hit counter to your Website.

54 pageviews

This is a simple PHP backend counter that displays the number of pageviews. You can style it however you like. It won't reset when multiple requests are made at the same time because of PHP's LOCK_EX and LOCK_UN code that doesn't allow access to the data file by multiple visitors simultaniously. This counter also uses PHP number_format to add comma separators when the counter is over 1,000.

Keep in mind that this records all pageviews including bots.

Source Code

PHP

$count_txt = 'counter.txt';
$dat = file_get_contents($count_txt);
if ($dat !== false)
{
$fil = fopen($count_txt, "w");
if (flock($fil, LOCK_EX)) {
echo '',number_format($dat+1),' pageviews';
fwrite($fil, $dat+1);
flock($fil, LOCK_UN);
}
fclose($fil);
}