Simple multi-domain counter with Redis and PHP
June 2, 2021 ≈ 1 minute 8 seconds
Imagine you have multiple domains on your server and you want to add a simple counter to count views and visits.
In this tutorial, I’m going to describe how to implement views and visits counter with PHP and Redis. It would be the most simple solution without bots detection, just visits and views. So, let's start!
First, install phpredis extention via composer:
composer require predis/predis
Now let's write getUserIp() function, which gets visitor ip address:
function getUserIP() {
$user_ip = getenv('REMOTE_ADDR')
or getenv('HTTP_CLIENT_IP')
or $user_ip = getenv('HTTP_X_FORWARDED_FOR');
return preg_replace('|[^0-9.]+|', '', $user_ip); // only digits and dots allowed
}
Initialize Redis, get IP and set up domain address:
$client = new Predis\Client();
$user_ip = getUserIP();
$domain = 'yourdomain';
Now, when all preparation is done, let's move to the counting:
if (!$client->sismember("ips:$domain", $user_ip)) { // if no ip in ips:subdomain
$client->hincrby("stat:$domain", 'visits', 1); // add visit
$client->sadd("ips:$domain", [$user_ip]); // add ip to the set
}
$client->hincrby("stat:$domain", 'views', 1); // add view
We used Redis Sets (collections of unique, unsorted string elements) to store IP addresses and Hashes (maps composed of fields associated with values) for counting.
Now to get counted visits and views use hget() function:
echo 'visits: ' . $client->hget("stat:$domain", 'visits') . '<br>';
echo 'views: ' . $client->hget("stat:$domain", 'views') . '<br>';
And don't forget to store values and flush Redis (flushall
command) at the end of the day.
You didn't provide any data, entered invalid email or already subscribed.
Try again. And if you still can't subscribe—write us.
Address successfully subscribed!
Subscribe to our newsletter
If you provide url of your website, we send you free design concept of one element (by our choice)
Subscribing to our newsletter, you comply with subscription terms and Privacy Policy