W3docs

How do I count unique visitors to my site?

There are several ways to count unique visitors to a website using PHP, but one common method is to use cookies.

There are several ways to count unique visitors to a website using PHP, but one common method is to use cookies.

  1. Set a cookie on the user's browser when they first visit your site.
  2. Check for the existence of this cookie on subsequent page loads.
  3. If the cookie does not exist, increment a counter and set the cookie.
  4. If the cookie does exist, do not increment the counter.
// Example: Cookie-based tracking
if (!isset($_COOKIE['unique_visitor'])) {
    // Increment your storage counter here
    increment_visitor_count();
    // Set cookie with expiration (e.g., 30 days) and path
    setcookie('unique_visitor', '1', time() + (86400 * 30), '/');
}

You can also use IP address to identify unique visitors, but this method has limitations as many users share IP addresses. Additionally, NAT and corporate proxies often mask individual users, and tracking IPs may require GDPR compliance or explicit user consent depending on your jurisdiction.

Another way to do this is by using sessions instead of cookies. You can set a session variable when a new user visits your site and check for the existence of this session variable on subsequent page loads. If the session variable does not exist, increment a counter and set the session variable. If the session variable does exist, do not increment the counter.

// Example: Session-based tracking
session_start();
if (!isset($_SESSION['visited'])) {
    increment_visitor_count();
    $_SESSION['visited'] = true;
}

You can also use a database to store the unique visitor count. You can store the user's IP address and a timestamp in a table and check for the existence of a matching IP address with a timestamp that is within a certain time frame (i.e. the last 24 hours). If a match is not found, increment the visitor count in the database and insert the IP address and timestamp.

-- Example table schema
CREATE TABLE visitors (
    id INT AUTO_INCREMENT PRIMARY KEY,
    ip_address VARCHAR(45) NOT NULL,
    visited_at DATETIME NOT NULL
);
// Example: Database check and insert (PDO)
$pdo = new PDO('mysql:host=localhost;dbname=yourdb', 'user', 'pass');
$ip = $_SERVER['REMOTE_ADDR'];
$cutoff = date('Y-m-d H:i:s', strtotime('-24 hours'));

$stmt = $pdo->prepare("SELECT COUNT(*) FROM visitors WHERE ip_address = ? AND visited_at > ?");
$stmt->execute([$ip, $cutoff]);
if ($stmt->fetchColumn() == 0) {
    // Increment global counter
    increment_visitor_count();
    $pdo->prepare("INSERT INTO visitors (ip_address, visited_at) VALUES (?, NOW())")->execute([$ip]);
}

Note: Regularly clean up old records (e.g., via a cron job) to prevent the table from growing indefinitely.