Retrieving Visitor IP Addresses Behind Cloudflare in PHP
When using Cloudflare for your website, you may notice that the IP addresses logged by PHP are those of Cloudflare's servers rather than the actual visitors. This is due to Cloudflare acting as a reverse proxy. To retrieve the original IP address of your users, you can utilize the HTTP_CF_CONNECTING_IP header provided by Cloudflare.
Steps to Retrieve the Real IP Address
- Check for Cloudflare Headers: First, ensure that the request is coming through Cloudflare by checking for specific headers.
- Set the Remote Address: If the headers are present, you can set
$_SERVER['REMOTE_ADDR']to the value of$_SERVER['HTTP_CF_CONNECTING_IP'].
Example Code
Here’s a simple PHP script to achieve this:
<?php
// Function to determine if the request is from Cloudflare
function isCloudflareRequest() {
return isset($_SERVER['HTTP_CF_CONNECTING_IP']);
}
// Function to get the real visitor IP address
function getVisitorIP() {
if (isCloudflareRequest()) {
// Return the real IP address from Cloudflare header
return $_SERVER['HTTP_CF_CONNECTING_IP'];
}
// Fallback to the default remote address
return $_SERVER['REMOTE_ADDR'];
}
// Usage
$visitorIP = getVisitorIP();
echo "Visitor's IP Address: " . $visitorIP;
?>
Important Considerations
- Security: Ensure that your server is configured to only accept requests from Cloudflare IP ranges to prevent IP spoofing. You can find the list of Cloudflare's IP ranges in their official documentation.
- Logging: Use the retrieved IP address for logging or analytics purposes as needed.
By following these steps, you can effectively track and log the actual IP addresses of your visitors while utilizing Cloudflare's services.