Quick fix for Cloudflare and PHP REMOTE_ADDR IP Detection

Some CMS-s, Frameworks, Custom Codes have built-in functions on collecting user logs (registrations, updates, submits, payments etc.) where they are using PHP’s $_SERVER[“REMOTE_ADDR”] variable to get the visitor’s IP address.

But as you know very popular Cloudflare Cloud Service passes all your traffic through its own servers – and that’s why all log function which i mentioned above writes Cloudflare’s IP address to the DataBase, not visitor’s actual IP address.

What to do for that.

As it is very common case, of course Cloudflare provides an alternative variable for that. It is called $_SERVER[“HTTP_CF_CONNECTING_IP”].

So if we are writing a code from scratch, we can use simple universal code to get the visitor IP:

if (!empty($_SERVER["HTTP_CF_CONNECTING_IP"])){
  $real_ip=$_SERVER["HTTP_CF_CONNECTING_IP"];
}
else {
 $real_ip=$_SERVER["REMOTE_ADDR"] ;
}

But what if we are working with existing code, core, class, FW, CMS? We can’t just to get and replace all $_SERVER[“REMOTE_ADDR”] variables with correct one.

The only thing we need is to fix it at initialization process.

Let’s write an example for WordPress.

wp-config.php is very good place to put your custom codes that will take an effect before WordPress init starts.

Just put this code piece to your wp-config.php file, and that’s all. REMOTE_ADDR variables will work OK everywhere inside WordPress (themes, plugins, core etc.)

if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
  $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
}
Get more useful WP tricks and snippets by subscribing to my mailclub.

One Reply to “Quick fix for Cloudflare and PHP REMOTE_ADDR IP Detection”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.