Home  >  Article  >  Database  >  How to Count Unique Visitors to Your Site Using PHP?

How to Count Unique Visitors to Your Site Using PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-08 09:50:02578browse

How to Count Unique Visitors to Your Site Using PHP?

How do I count unique visitors to my site?

Problem:

I need a precise visitor counter that only records distinct visitors, whether they visit daily or weekly, for a user post system that ranks the most viewed posts on the homepage. Using Google Analytics is not an option.

Solution:

This PHP code implements the required functionality:

<?php
session_start();        // start Session, if not already started

$visitors = array();    // store visitors IP addresses in a PHP array

$ip = $_SERVER['REMOTE_ADDR']; // get visitor's IP address

$dt = time();             // get current timestamp

$expiration = 86400;        // expire session in 24 hours

if(isset($_GET['view'])) { // check if 'view' is a query parameter
    if(!isset($_SESSION['last_visit']) || ($_SESSION['last_visit'] < ($dt - $expiration))) {
        // visitor hasn't visited in the last 24 hours (or ever)
        $_SESSION['last_visit'] = $dt;  // update last visit timestamp
        $visitors[] = $ip;            // add IP to the visitors array
        $view_count = $view_count + 1; // increment view count
    }
}

// output data
echo 'Total Unique Visitors: ', count($visitors);
echo '<br>';
echo 'Total Page Views: ', $view_count;
?>

How it works:

  1. Initialize a PHP array $visitors to store unique IP addresses.
  2. Get the visitor's IP address using $_SERVER['REMOTE_ADDR'].
  3. Get the current timestamp ($dt).
  4. Set a session variable $_SESSION['last_visit'] to track the last time the visitor viewed the page, with an expiration time of 24 hours.
  5. Check if 'view' is a query parameter. If it is, it means the page is being viewed.
  6. If the visitor hasn't visited in the last 24 hours (or ever), update the $_SESSION['last_visit'] timestamp, add the IP to $visitors, and increment the view count.
  7. Output the total number of unique visitors (count of $visitors) and the total page views ($view_count).

Remember: For this code to work, you need to include it on every page you want to track views for, and you need to add the following HTML code to the pages:

<a href="?view=1">View Post</a>

The above is the detailed content of How to Count Unique Visitors to Your Site Using PHP?. 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