Here is a simple and robust PHP script that counts unique visitors by IP address, storing the data in text files. This approach avoids using a database and is ideal for small-scale or local applications.
✅ Features:
- Stores each unique IP address once.
- Uses two files:
visited_ips.txt: stores all counted IP addresses.
count.txt: stores the total number of unique visitors.
- Handles file creation and initialization automatically.
- Prevents duplicate entries and race conditions (basic handling).
📁 File Structure (Example):
your-project/
├── index.php
├── visited_ips.txt
└── count.txt
✅ PHP Code
<?php
// Get the visitor's IP address
$ip = $_SERVER['REMOTE_ADDR'];
// Define file paths
$ipsFile = 'visited_ips.txt';
$countFile = 'count.txt';
// Ensure the IPs file exists
if (!file_exists($ipsFile)) {
touch($ipsFile);
}
// Ensure the count file exists
if (!file_exists($countFile)) {
file_put_contents($countFile, '0');
}
// Read existing IPs from the file
$ips = file($ipsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// Check if the IP is already in the list
if (!in_array($ip, $ips)) {
// Append the new IP to the file
file_put_contents($ipsFile, $ip . PHP_EOL, FILE_APPEND);
// Read the current count
$count = (int)file_get_contents($countFile);
$count++;
// Write the updated count
file_put_contents($countFile, $count);
}
// Output the total number of unique visitors
echo "Total unique visitors: " . file_get_contents($countFile);
?>
🧠 Notes and Considerations
-
IP Address Handling:
- Uses
$_SERVER['REMOTE_ADDR'] — which is the most reliable way to get the client IP unless behind a proxy.
- For proxies, consider using
HTTP_X_FORWARDED_FOR, but be cautious of spoofing.
-
File Locking:
- This script does not include file locking, which could cause issues in high-traffic environments.
- For production use, consider using a database (e.g., MySQL) with a unique constraint on the
ip field.
-
Scalability:
- This solution is suitable for small-scale applications.
- For larger systems, use a database and store the count in a dedicated table.
-
Security:
- Ensure that the
visited_ips.txt and count.txt files are not publicly accessible via the web server.
🔄 Example Output (after first visit):
Total unique visitors: 1
After a second visit:
Total unique visitors: 1
🛠️ Optional Enhancements
- Store IP addresses in a JSON array instead of plain text for more structured data.
- Add logging or error handling for file operations.
- Use sessions or cookies for additional tracking (but this is not needed for IP-only counting).
Would you like a version that uses a MySQL database instead?