PHP Visitor Counter Script

Build a PHP visitor counter script in 2025. Easy step-by-step guide for analytics.

PHP Visitor Counter Script

Many websites show how many users have visited them. This is called a visitor counter. In this post, you will learn how to create a simple visitor counter using PHP and MySQL.

We will also make sure:

  • Only unique users per session are counted
  • The counter works with sessions
  • Code is safe and not open to security risks
  • The visitor number is displayed to the user on the frontend

This tutorial is very easy to understand, even if you're a new developer or just starting with PHP.

📋 What Is a Visitor Counter?

A visitor counter is a script that counts how many people have visited your website. Each time a new user visits your site (not a page refresh), the count increases by 1.

Example:

  • User A visits your site → count is 1
  • User A refreshes the page → count is still 1 ✅
  • User B visits → count is 2
  • User A comes again after a few hours (new session) → count is 3

 

🛠️ What You Need Before Starting

  • PHP installed (XAMPP, WAMP, or live server)
  • MySQL database
  • A basic idea of PHP and MySQL
  • We will create a file called counter.php

 

🗃️ Step 1: Create a Database Table

Create a table to store visitor counts. We only need one row in this table.

CREATE TABLE visitor_counter (
  id INT AUTO_INCREMENT PRIMARY KEY,
  counts INT NOT NULL DEFAULT 0
);

 

🧾 Step 2: Create PHP File with Visitor Logic and Display

Create a new file called counter.php and paste the full code below:

<?php
session_start(); // Start session to track the visitor

$visitorNumber = 0; // Variable to store visitor number

if (!isset($_SESSION['visitor_tracked'])) {

    // Database connection variables
    $host = 'localhost';
    $user = 'root';
    $pass = '';
    $dbname = 'test';

    // Create connection
    $conn = new mysqli($host, $user, $pass, $dbname);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    // Get current count
    $stmt = $conn->prepare("SELECT counts FROM visitor_counter WHERE id = 1");
    $stmt->execute();
    $stmt->bind_result($currentCount);
    $stmt->fetch();
    $stmt->close();

    if ($currentCount === null) {
        // First visitor ever
        $visitorNumber = 1;
        $stmt = $conn->prepare("INSERT INTO visitor_counter (id, counts) VALUES (1, ?)");
        $stmt->bind_param("i", $visitorNumber);
        $stmt->execute();
        $stmt->close();
    } else {
        // Not first visitor
        $visitorNumber = $currentCount + 1;
        $stmt = $conn->prepare("UPDATE visitor_counter SET counts = ? WHERE id = 1");
        $stmt->bind_param("i", $visitorNumber);
        $stmt->execute();
        $stmt->close();
    }

    // Mark this session as tracked
    $_SESSION['visitor_tracked'] = true;

    // Close DB
    $conn->close();
} else {
    // Already tracked, fetch current number to show
    $conn = new mysqli('localhost', 'root', '', 'test');
    $result = $conn->query("SELECT counts FROM visitor_counter WHERE id = 1");
    $row = $result->fetch_assoc();
    $visitorNumber = $row['counts'];
    $conn->close();
}
?>

<!DOCTYPE html>
<html>
<head>
  <title>Visitor Counter</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      padding: 40px;
      text-align: center;
    }
    .visitor-box {
      display: inline-block;
      padding: 20px 40px;
      font-size: 20px;
      background: #f2f2f2;
      border-radius: 12px;
      box-shadow: 0 0 8px rgba(0,0,0,0.1);
    }
  </style>
</head>
<body>

  <div class="visitor-box">
    <?php echo "You are visitor number: <strong>" . $visitorNumber . "</strong>"; ?>
  </div>

</body>
</html>

 

🧪 How It Works

  • Only new users (or users with expired sessions) increase the count
  • The same user during one session is not counted multiple times
  • The visitor number is shown with a clean HTML design

 

🔐 Security Tips

We always want to write code that is safe and secure. Even if the script looks small, we should still follow best practices.

  • ✅ Prepared Statements:
    All database queries in this script use prepare() and bind_param(). This method helps protect your site from SQL injection attacks. Even though we're not using user input here, it's a good habit to always use prepared statements.
  • ✅ Session Tracking:
    We use PHP session_start() to make sure the same visitor is not counted again and again. Once a user is counted, a session variable is saved, so they are not counted again during the same session.
  • ✅ No Direct User Input:
    This script does not accept any values from users (like forms or query strings). That means there is no risk of someone entering bad data into the system from outside.

These small steps make sure your visitor counter is safe, clean, and ready for real websites.

 

🧠 Final Thoughts

And that’s it! You have now created a working PHP visitor counter script with:

  • MySQL for storing counts
  • Sessions to avoid double counts
  • Frontend display showing the visitor number

Now you know how to display visitor counter on website.This is beginner-friendly and works great on basic websites. You can also improve it later by tracking daily visits, unique IPs, or using Redis for faster performance.

If you liked this tutorial, feel free to bookmark it or share it with your developer friends!

 

0 Comments
Leave a Comment