Implementing Unique Visitor Counting with PHP and MySQL

Dec 07, 2025 · Programming · 8 views · 7.8

Keywords: PHP | MySQL | visitor counting | unique visitors | GDPR

Abstract: This article explores techniques for counting unique visitors to a website using PHP and MySQL, covering text file and database storage methods with code examples, and discussing enhancements like cookie usage, proxy detection, and GDPR compliance for robust implementation.

Introduction

Accurately counting unique visitors is essential for displaying popular content on websites. Traditional methods often miscount due to page refreshes, necessitating time-based identification (e.g., daily or weekly). This article synthesizes the best answer from the QA data with supplementary insights to provide a comprehensive guide.

Method 1: Text File-Based Implementation

Using a text file for storage offers a lightweight approach. First, create a file (e.g., userson.txt) with CHMOD 0777 permissions for PHP write access. Then, develop a PHP script that checks sessions, retrieves visitor identifiers (e.g., IP address or session name), manages time windows, and updates data. The following code rewrites the core logic from the best answer.

<?php
if (!isset($_SESSION)) session_start();
$filetxt = 'userson.txt';
$timeon = 120;
$sep = '^^';
$vst_id = '-vst-';
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR'] . $vst_id;
$addrow = array();
$addrow[] = $uvon . $sep . time();
if (is_writable($filetxt)) {
    $ar_rows = file($filetxt, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($ar_rows as $row) {
        $ar_line = explode($sep, $row);
        if ($ar_line[0] != $uvon && (intval($ar_line[1]) + $timeon) >= time()) {
            $addrow[] = $row;
        }
    }
}
file_put_contents($filetxt, implode("\n", $addrow));
$nrvst = 0;
foreach ($addrow as $item) {
    if (preg_match('/^([0-9\.]*)' . $vst_id . '/i', $item)) $nrvst++;
}
echo 'Online: ' . count($addrow) . ', Visitors: ' . $nrvst;
?>

This method is easy to deploy but may face file-locking issues under high concurrency. Supplementary answers suggest using cookies for better accuracy by setting expiration times to enforce time limits.

Method 2: MySQL Database-Based Implementation

For applications requiring reliable data management, a MySQL table is preferable. First, create a table named userson with columns uvon (user identifier) and dt (timestamp). The PHP script should perform three SQL operations: delete old records, insert or update current visitors, and query online counts. The code below rewrites the best answer's approach.

<?php
if (!isset($_SESSION)) session_start();
$host = 'localhost';
$user = 'root';
$pass = 'password';
$dbname = 'database';
$conn = new mysqli($host, $user, $pass, $dbname);
if ($conn->connect_error) die('Connection failed');
$timeon = 120;
$dt = time();
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR'] . '-vst-';
$conn->query("DELETE FROM userson WHERE dt < " . ($dt - $timeon));
$conn->query("INSERT INTO userson (uvon, dt) VALUES ('" . $uvon . "', " . $dt . ") ON DUPLICATE KEY UPDATE dt=" . $dt);
$result = $conn->query("SELECT * FROM userson");
$nrvst = 0;
while ($row = $result->fetch_assoc()) {
    if (preg_match('/^([0-9\.]*)' . '-vst-' . '/i', $row['uvon'])) $nrvst++;
}
$conn->close();
echo 'Online: ' . $result->num_rows . ', Visitors: ' . $nrvst;
?>

This solution supports complex queries and scalability but adds database overhead. Additional answers recommend IP detection functions to handle proxies, such as using the HTTP_X_FORWARDED_FOR header.

Enhancements and Compliance Considerations

Unique visitor counting must balance accuracy with privacy. Cookies can mitigate IP sharing issues but may be disabled by clients. IP-based methods require GDPR compliance: since 2016, the EU treats IP addresses as personal data, so storage should involve hashing for anonymity, e.g., using md5($_SERVER['REMOTE_ADDR']). Time windows (e.g., 24 hours) should align with business needs.

Conclusion

For implementing unique visitor counts, choose storage based on site scale: text files suit small sites for simplicity, while MySQL ensures data integrity for larger applications. Combining cookies with IP hashing improves accuracy and legal adherence. Developers should test code regularly and use sessions to distinguish logged-in users. By integrating these techniques, one can build efficient and compliant visitor statistics systems.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.