Being able to count the number of visitors on each web page of your website will definitely help you in multiple ways. The most important one is that it allows you to understand what people are looking for on your website. In this tutorial, I’ll guide you about how you can add a website visitor counter on your own website in a step by step manner.
I’ll be using PHP and MySQL for the basic functionality but also use a little bit HTML5 code to depict a real-world scenario.
Just in case you are new to the Web Development field and want to earn money by creating professional websites. Then, I would highly recommend you to take these courses from Udemy.
Anyways, let’s take a look at what you will be learning in this tutorial.
Basically we need a database for two purposes. First of all we will use it to store data for each web page of our website. Secondly we have to keep a record of previous visitors which help us figure out whether the new visitor is unique or not.
Let’s open your phpMyAdmin and create a database named “website_visitor_counter”. Or simply use the below SQL query.
CREATE DATABASE website_visitor_counter;
Now move on and add two tables “pages” and “page_views” in the newly created database. You can make use of the below SQL queries.
CREATE TABLE pages ( id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, total_views INTEGER UNSIGNED NOT NULL, PRIMARY KEY (id) );
CREATE TABLE page_views ( visitor_ip VARCHAR(255) NOT NULL, page_id INTEGER UNSIGNED NOT NULL, FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE ON UPDATE CASCADE );
In this tutorial we will be counting hits on three web pages. So, let’s add three rows in the “pages” table (one row for each web page). Use the below SQL INSERT query.
INSERT INTO pages (total_views) VALUES (0),(0),(0);
Create these files and folder before proceeding to next step.
Connecting to a MySQL database using PHP is a really simple and straightforward procedure. Copy/Paste the below PHP code inside your “db_connect.php” file and save it.
<?php $db_host = "localhost"; // Database Host $db_user = "root"; // Database User $db_pass = ""; // Database Password $db_name = "website_visitor_counter"; // Database Name $conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name); // Connect to Database if(!$conn) // Check connection { die("Connection failed: " . mysqli_connect_error()); // Display error if not connected } ?>
A point to be noted is that you may need to change the values of above PHP variables according to your specific environment.
Now it’s time to take a look at the core part of this project where we will be creating three PHP functions to define the logic and handle the overall functionality of a website hit counter.
Here’s the contents of our “functions.php” file.
<?php function total_views($conn, $page_id = null) { if($page_id === null) { // count total website views $query = "SELECT sum(total_views) as total_views FROM pages"; $result = mysqli_query($conn, $query); if(mysqli_num_rows($result) > 0) { while($row = $result->fetch_assoc()) { if($row['total_views'] === null) { return 0; } else { return $row['total_views']; } } } else { return "No records found!"; } } else { // count specific page views $query = "SELECT total_views FROM pages WHERE id='$page_id'"; $result = mysqli_query($conn, $query); if(mysqli_num_rows($result) > 0) { while($row = $result->fetch_assoc()) { if($row['total_views'] === null) { return 0; } else { return $row['total_views']; } } } else { return "No records found!"; } } } function is_unique_view($conn, $visitor_ip, $page_id) { $query = "SELECT * FROM page_views WHERE visitor_ip='$visitor_ip' AND page_id='$page_id'"; $result = mysqli_query($conn, $query); if(mysqli_num_rows($result) > 0) { return false; } else { return true; } } function add_view($conn, $visitor_ip, $page_id) { if(is_unique_view($conn, $visitor_ip, $page_id) === true) { // insert unique visitor record for checking whether the visit is unique or not in future. $query = "INSERT INTO page_views (visitor_ip, page_id) VALUES ('$visitor_ip', '$page_id')"; if(mysqli_query($conn, $query)) { // At this point unique visitor record is created successfully. Now update total_views of specific page. $query = "UPDATE pages SET total_views = total_views + 1 WHERE id='$page_id'"; if(!mysqli_query($conn, $query)) { echo "Error updating record: " . mysqli_error($conn); } } else { echo "Error inserting record: " . mysqli_error($conn); } } } ?>
In this section we will be creating four web pages to count unique visitors on our website. The files used for these web pages are as follow:
Also remember that I’ve used two more files “header.php” and “footer.php” just to separate the header and footer section of our web pages. This way we will be able to reuse same code in multiple files and it makes it very easy to edit as we just need to modify one file.
Basically the “header.php” file contains few links to navigate on different web pages of this project. Here’s the code for this file.
<!DOCTYPE html> <html> <head> <title>Website Visitor Counter</title> </head> <body> <header> <ul> <li><a href="index.php">Main Page</a></li> <li><a href="page_1.php">Page 1</a></li> <li><a href="page_2.php">Page 2</a></li> <li><a href="page_3.php">Page 3</a></li> </ul> </header>
“footer.php” only contains few ending tags of our web pages. Check the code below:
</body> </html>
“index.php” file is just like the main/home page of a website. We will only use it to display total website views. Here’s the code for this file.
<?php require_once('includes/db_connect.php'); // Database connection file require_once('includes/functions.php'); // PHP functions file ?> <!-- header file --> <?php require_once('includes/header.php'); ?> <div> <?php $total_website_views = total_views($conn); // Returns total website views echo "<strong>Total Website Views:</strong> " . $total_website_views; ?> </div> <div style="color: red;">Note: This page only displays the total views of website.<div> <!-- footer file --> <?php require_once('includes/footer.php'); ?>
Does this code looks complex? Don’t worry! Let me explain…
“page_1.php”, “page_2.php” and “page_3.php” are like other web pages on a website. So, we are going to track them separately just to show you the correct method of how you should implement website visitor counter on your personal or business website.
<?php require_once('includes/db_connect.php'); // Database connection file require_once('includes/functions.php'); // PHP functions file $page_id = 1; $visitor_ip = $_SERVER['REMOTE_ADDR']; // stores IP address of visitor in variable add_view($conn, $visitor_ip, $page_id); ?> <!-- header file --> <?php require_once('includes/header.php'); ?> <div> <?php $total_page_views = total_views($conn, $page_id); // Returns total views of this page echo "<strong>Total Views of this Page:</strong> " . $total_page_views; ?> </div> <!-- footer file --> <?php require_once('includes/footer.php'); ?>
<?php require_once('includes/db_connect.php'); // Database connection file require_once('includes/functions.php'); // PHP functions file $page_id = 2; $visitor_ip = $_SERVER['REMOTE_ADDR']; // stores IP address of visitor in variable add_view($conn, $visitor_ip, $page_id); ?> <!-- header file --> <?php require_once('includes/header.php'); ?> <div> <?php $total_page_views = total_views($conn, $page_id); // Returns total views of this page echo "<strong>Total Views of this Page:</strong> " . $total_page_views; ?> </div> <!-- footer file --> <?php require_once('includes/footer.php'); ?>
<?php require_once('includes/db_connect.php'); // Database connection file require_once('includes/functions.php'); // PHP functions file $page_id = 3; $visitor_ip = $_SERVER['REMOTE_ADDR']; // stores IP address of visitor in variable add_view($conn, $visitor_ip, $page_id); ?> <!-- header file --> <?php require_once('includes/header.php'); ?> <div> <?php $total_page_views = total_views($conn, $page_id); // Returns total views of this page echo "<strong>Total Views of this Page:</strong> " . $total_page_views; ?> </div> <!-- footer file --> <?php require_once('includes/footer.php'); ?>
“page_1.php”, “page_2.php” and “page_3.php” are almost similar to the “index.php” file with few exceptions.
We evaluated the performance of Llama 3.1 vs GPT-4 models on over 150 benchmark datasets…
The manufacturing industry is undergoing a significant transformation with the advent of Industrial IoT Solutions.…
If you're reading this, you must have heard the buzz about ChatGPT and its incredible…
How to Use ChatGPT in Cybersecurity If you're a cybersecurity geek, you've probably heard about…
Introduction In the dynamic world of cryptocurrencies, staying informed about the latest market trends is…
The Events Calendar Widgets for Elementor has become easiest solution for managing events on WordPress…
View Comments
The php website says that total_views() doesn't exist!
Thanks, just getting back into web programming and this was a big help. Nice set of PHP code. It will work well for me and can be adapted to many uses. There are a lot of counters out there but this is better solution. I will be adapting it to a like / unlike counter as well. Counters that do not do the IP comparison are not as useful. Also when they count my visits to my page it gets unruly.
Thank you very much. This is really helpful and saved me much of my time.
Thank you so much.
CREATE TABLE VIEWS_views
( visitor_ip VARCHAR(255) NOT NULL,
page_id INTEGER UNSIGNED NOT NULL,
FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE ON UPDATE CASCADE)
O this was perfect. I made some changes to mine, but the core remains the same.
I will later convert his to a flatfile style for ease of moving site. but ya this was great.
(check it out here appgetmgr.com ) credit is in the webpage source
Thanks a lot.
This fails to get the records in the tables. Also, the connection does not work.
note: in official version this line does not work:
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name); // Connect to Database
but this line, which I changed it to, does work:
$conn = new mysqli($db_host, $db_user, $db_pass, $db_name); // Connect to Database
Looks great, but how do you implement it? In my root directory I already have a file index.php, which is the site's home page. Do I embed the text of your index.php file inside the homepage? I tried that, but it doesn't seem to increment the views in the db.
pls help thanks
yeah how do you implement this pls
Thank you so much! It's really very useful for me
You're welcome Rajat. I'm pleased to hear that. :)
Replacing >>>
else
{
return "No records found!";
}
by >>>
else
{
$query = "INSERT INTO pages (id, total_views) VALUES ($page_id, '1')";
$result = mysqli_query($conn, $query);
}
will insert the page id and return "1" to counter, case it is a new page whose id is not previously listed in the table.