Welcome to lark3ri.fi

Visitor counter with PHP and MySQL

18.09.2020

Do you remember, in the old days, many sites had those little numbers that at its finest even looked like a 7seg screens with few digits that counted the number of times that the page was loaded. Each time you reloaded the page, one more was added to that counter number what it showed.

I made exactly that, and here is the code of it and how you can get it to work on your own website too. This code also includes that it prevents users to increase the counter number by repeatedly reloading the page again and again. However, this doesn't look like a 7seg screen but is just plain numbers. You need MySQL and PHP to get this to work on your website. Next, a little guide on how to make this working. You still need at least a basic understanding of how PHP and MySQL works:

Firstly, create a MySQL user account which you plan to use with this. Remember to use strong passwords, always. Secondly, create a new database and name it ip-addresses and add basic SELECT,INSERT,UPDATE,DELETE privileges to your firstly created user to access this database. Thirdly, run the MySQL code below in the MySQL console, inside that database:

sqlcommand.sql
CREATE TABLE IF NOT EXISTS `ip-addresses` (
	ip VARCHAR(100) NOT NULL,
	UNIQUE KEY unique_ip(ip)
);

Lastly, you can put this PHP code somewhere in the code of your web pages, fill it in with the correct login information, and use a variable $ip_counter_value to show the number of visitors on your webpage.

phpvisitorcounter.php
<?php
$ip_counter_value = "00000000";
$server_name = "localhost";
$user_name = "user";
$password = "password";
$db_name = "ip-addresses";

$conn = mysqli_connect($server_name, $user_name, $password, $db_name);
if($conn !== false) {
	$client_ip = htmlspecialchars($_SERVER['REMOTE_ADDR'], ENT_QUOTES);
	$client_ip = mysqli_real_escape_string($conn, $client_ip);
	
    $sql = "INSERT INTO `" . $db_name . "`(`ip`) VALUES ('" . $client_ip . "')";
	mysqli_query($conn, $sql);
	
	$sql = "SELECT `ip` FROM `" . $db_name . "` ORDER BY `ip`";
	$res = mysqli_query($conn, $sql);
	
	$row_count = mysqli_num_rows($res);
	mysqli_close($conn);
	$ip_counter_value = str_pad($row_count, 8, "0", STR_PAD_LEFT);
}
?>
« Back | ↑ Top