Logging Visitor IPs with Cloudflare in PHP

When using Cloudflare, it’s important to properly log the original visitor’s IP address. By default, Cloudflare passes the visitor’s IP address through the HTTP_CF_CONNECTING_IP header, rather than the typical REMOTE_ADDR. Here’s a simple PHP script modification to handle this correctly.

The PHP Script

Below is the PHP script that checks for the Cloudflare IP header and logs the visitor’s IP address along with a timestamp:

} else {
    $ip = $_SERVER['REMOTE_ADDR'];

$timestamp = date('Y-m-d H:i:s');
$log_entry = $timestamp . " - " . $ip . "\n";

file_put_contents('traffic.txt', $log_entry, FILE_APPEND);

How It Works

  1. Check for Cloudflare Header: The script first checks if the HTTP_CF_CONNECTING_IP header is set. This header contains the original visitor’s IP address when the request is routed through Cloudflare.
  2. Fallback to REMOTE_ADDR: If the Cloudflare header is not set, the script falls back to using REMOTE_ADDR, which is the default way to get the client’s IP address in PHP.
  3. Log the IP with Timestamp: It then creates a log entry that includes the current timestamp and the determined IP address.
  4. Append to Log File: Finally, it appends this log entry to a file named traffic.txt.