A safe click counter in PHP: atomic updates and no open redirect
Disclosure: I make WaBio at Murabyte, which is mentioned at the end. Click counters look easy: add one to a number when someone clicks. The details decide whether the numbers are right and whether the link is safe. Here
Disclosure: I make WaBio at Murabyte, which is mentioned at the end.
Click counters look easy: add one to a number when someone clicks. The details decide whether the numbers are right and whether the link is safe. Here is a small PHP redirect that does both.
The idea
Instead of linking straight to the destination, your page links to go.php?id=12. The script counts the click, then redirects.
<?php
$id = (int)($_GET['id'] ?? 0);
$st = $pdo->prepare("SELECT url FROM links WHERE id = ? AND active = 1");
$st->execute([$id]);
$url = $st->fetchColumn();
if (!$url || !preg_match('#^https?://#i', $url)) {
http_response_code(404);
exit('Not found');
}
$pdo->prepare(
"INSERT INTO clicks (link_id, day, n) VALUES (?, CURDATE(), 1)
ON DUPLICATE KEY UPDATE n = n + 1"
)->execute([$id]);
header('Location: ' . $url, true, 302);
exit;
Why it is written this way
-
Atomic counter.
ON DUPLICATE KEY UPDATE n = n + 1lets the database add one. Reading the number, adding one in PHP and writing it back can lose clicks when two people click together. It needs a unique key on(link_id, day). -
Only http and https. If an admin (or an attacker with admin access) saves a
javascript:URL, a redirect could do harm. Check the scheme before redirecting. -
Look up by id, not by URL in the query string. A script that redirects to any
?url=value is an open redirect that others can abuse in phishing links. - Daily counters only. You can see which links work without storing anything about each visitor.
What to show on the dashboard
Page views per day, clicks per link per day, and the top five links. That is enough to decide which links to keep.
A ready-made version
WaBio is a self-hosted PHP/MySQL link-in-bio page I make at Murabyte: Arabic (RTL) and English, themes, a WhatsApp button (a plain wa.me link), per-link daily click stats, and a print-ready QR page generated in the browser. One bio page per installation, hosting not included. Regular license $19: https://murabyte.gumroad.com/l/wabio-arabic-link-in-bio
php #mysql #webdev #security #murabyte
Written with AI assistance and reviewed by Murabyte.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.