Home  >  Article  >  Database  >  How Can I Track Unique Visitors to My Website with PHP and MySQL?

How Can I Track Unique Visitors to My Website with PHP and MySQL?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-17 13:03:01768browse

How Can I Track Unique Visitors to My Website with PHP and MySQL?

How Do I Count Unique Visitors to My Site?

Goal: Count unique visitors to your site, considering only one visit per user per day (or week).

Solution (PHP Code):

<?php
// Open database connection
$conn = new mysqli('localhost', 'root', 'password', 'database');

// Get user's IP address
$ip = $_SERVER['REMOTE_ADDR'];

// Check if user already visited today (or in the last week)
$sql = "SELECT * FROM visitors WHERE ip='$ip' AND last_visit >= DATE_SUB(NOW(), INTERVAL 1 DAY)";
$result = $conn->query($sql);

// If user is a new visitor
if ($result->num_rows == 0) {
    // Insert user's IP and current timestamp
    $sql = "INSERT INTO visitors (ip, last_visit) VALUES ('$ip', NOW())";
    $conn->query($sql);

    // Increment total visitor count
    $sql = "UPDATE stats SET visits = visits + 1";
    $conn->query($sql);
}

// Get total number of unique visitors
$sql = "SELECT COUNT(*) AS total_visitors FROM visitors";
$result = $conn->query($sql);
$total_visitors = $result->fetch_assoc()['total_visitors'];

// Display the number of unique visitors
echo "Total unique visitors: $total_visitors";

// Close database connection
$conn->close();
?>

Explanation:

  • The code establishes a database connection and retrieves the user's IP address.
  • It checks the database to determine if the user has already visited within the last day (or week).
  • If the user is new, their IP and current timestamp are recorded in the "visitors" table, and the total visit count in the "stats" table is incremented.
  • Finally, the number of unique visitors is queried from the "visitors" table and displayed to the user.

Alternative Resources:

  • Tutorial on counting unique website visitors using MySQL: [link to tutorial]

The above is the detailed content of How Can I Track Unique Visitors to My Website with PHP and MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn