A simple hit counter - M0YNG.uk
Created 2020-10-01
- Hacking
I don't have any analytics on this site, but it would still be nice to know if anyone is looking... and something reminded me of the hit counters we used to have back on the old web.
They were almost always a graphic which showed a number that increased every time that image was loaded, I don't think I ever made one so I'm not sure how exactly they worked.
I wondered if I could combine a bit of PHP, with a JSON file, some SVG, and good old HTTP headers to make a very simple page counter that would just work, and automatically handle new pages being added to the site.
Well, it seems that yes, I can.
Requirements / Limitations
- I wanted this to be as small and fast as possible.
- It should not need to know about a page before it starts counting.
- Ideally it would be accessible, meaning anyone can know the value.
- It should not require databases, etc.
The code
The PHP
This is the code that does all the work, I'm sure it could be better!
0) {
// strip out index.html so it is counted the same as /
if (substr($_SERVER['HTTP_REFERER'], -10) === 'index.html') {
$_SERVER['HTTP_REFERER'] = substr($_SERVER['HTTP_REFERER'], 0, strlen($_SERVER['HTTP_REFERER']) - 10);
}
// remove any trailing /s
$_SERVER['HTTP_REFERER'] = rtrim($_SERVER['HTTP_REFERER'], '/');
// sanitize the string
$pageHash = filter_var($_SERVER['HTTP_REFERER'], FILTER_SANITIZE_STRING);
// load the json file of counts
$counterData = json_decode(file_get_contents("counterData.json"), true);
// if it already exists
if (isset($counterData[$pageHash])) {
// add one to it
$counterData[$pageHash]++;
} else {
// otherwise, start counting at one
$counterData[$pageHash] = 1;
}
// cast that number to a string for later use
$thisCount = (string) $counterData[$pageHash];
// save the counting
file_put_contents("counterData.json", json_encode($counterData));
}
}
// below we have the SVG ... and inject our count with left padded zeros into the text area using php
?>
The HTML
To use the counter simply use an `<img>` tag like so
The JSON
It ends up looking a bit like this, which means I can grab the file and read it myself if I want, without having to visit every page to see a number.
{
"https:\/\/m0yng.uk": 3,
"https:\/\/m0yng.uk\/2020\/08\/The-Portable-Web": 2
}
Improvements?
It would be great to embed the SVG itself into the page, this would allow it to inherit font colours, etc. and be accessible as text to accessibility technology.
However, I'm not sure how to do that, whilst keeping it very simple to use.
-+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-
🖤 Black Lives Matter
💙🤍💜 Trans Rights are Human Rights
❤️🧡💛💚💙💜 Love is Love
Copyright © 2025 Christopher M0YNG - It is forbidden to use any part of this site for crypto/NFT/AI related projects.
Page generated 2025-08-07 by Complex 19