Write me php code for storing booleans per ip. Context I want a visitor counter, where I…
- User
Write me php code for storing booleans per ip. Context I want a visitor counter, where I only count every ip address once.
Assistant
Here's a PHP script that counts unique visitors by storing IP addresses in a file:
<?php // Get visitor's IP address $ip = $_SERVER['REMOTE_ADDR']; // File to store IP addresses $file = 'visitors.txt'; // Open file in append+read mode $fp = fopen($file, 'a+'); if ($fp) { // Lock the file for exclusive access flock($fp, LOCK_EX); // Read existing IPs rewind($fp); // Move pointer to start $currentIps = array(); while (!feof($fp)) { $line = fgets($fp); $trimmed = trim($line); if ($trimmed !== '') { $currentIps[] = $trimmed; } } // Check if IP already exists if (!in_array($ip, $currentIps)) { // Add new IP to the list and file $currentIps[] = $ip; fwrite($fp, $ip . "\n"); } // Unlock and close file flock($fp, LOCK_UN); fclose($fp); } // Display visitor count echo "Total unique visitors: " . count($currentIps); ?>How it works:
- IP Detection: Uses
$_SERVER['REMOTE_ADDR']to get the visitor's IP address - File Storage: Stores IP addresses in a text file (
visitors.txt) - File Locking: Uses flock() to prevent concurrent access issues
- IP Checking:
- Reads all existing IPs from the file
- Checks if current IP already exists
- Writing: Only writes the IP if it's new
- Counting: Shows total unique visitors
Notes:
- Works best for low to moderate traffic sites
- Stores IPs as one per line in the text file
- Automatically creates the file if it doesn't exist
- Handles concurrent requests safely with file locking
- Trims whitespace for reliability
To use:
- Save this code as a .php file (e.g.,
counter.php) - Ensure the web server has write permissions to the directory
- Visit the page and check the visitor count
For higher traffic or security-sensitive environments, consider using a database instead of a file-based solution.
- IP Detection: Uses
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.