Home > Database > Mysql Tutorial > body text

How can I create a PHP script to count unique website visitors with a daily limit?

Mary-Kate Olsen
Release: 2024-11-08 04:56:01
Original
862 people have browsed it

How can I create a PHP script to count unique website visitors with a daily limit?

How do I count unique visitors to my site?

Question:

I need a visitor counter that counts unique visitors to my site. By unique, I mean a person can only view a post once a day or week. Can you provide the PHP code for this?

Answer:

The below PHP code will count unique visitors to your site, limiting each visitor to one count per day:

<?php
// Initialize variables
$filePath = 'visitor_counts.txt';
$timeLimit = 86400; // One day in seconds (24 * 60 * 60)

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

// Read the visitor counts file
$visitorCounts = file_get_contents($filePath);

// Parse the visitor counts into an array
$visitorCountsArray = explode("\n", $visitorCounts);

// Check if the visitor's IP address is already in the array
if (in_array($ip, $visitorCountsArray)) {
  // Visitor has already been counted today
  echo "Visitor has already been counted today";
} else {
  // Add the visitor's IP address to the array
  $visitorCountsArray[] = $ip;

  // Update the visitor counts file
  file_put_contents($filePath, implode("\n", $visitorCountsArray));

  // Increment the visitor count
  $visitorCount++;
}

// Echo the visitor count
echo "Visitor count: $visitorCount";
?>
Copy after login

Explanation:

  • The PHP script reads visitor counts from a text file, visitor_counts.txt.
  • Each line in the text file represents a unique visitor's IP address.
  • If the visitor's IP address is already in the text file, they have already been counted today and the count is not incremented.
  • Otherwise, the IP address is added to the text file and the count is incremented.

The above is the detailed content of How can I create a PHP script to count unique website visitors with a daily limit?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template