WordPress – How to get visitor IP address over CloudFlare

When you’re running a website through CloudFlare you may notice that IP addresses being logged are not correct – that each IP address that your website logs will be from the ClareFlare network – not the visitor.

This is because ClareFlare acts as a reverse proxy, masking the typical ways of recording a visitors IP address.

In PHP (the code language powering WordPress) – this is normally done using $_SERVER[‘REMOTE_ADDR’]

To fix this you need to take advantage of a special server variable available to CloudFlare users –  $_SERVER[‘HTTP_CF_CONNECTING_IP’]

The code below shows how to use this server variable to fix WordPress IP address logging issues.

To use it I recommend you create a “must use” plugin containing the code – “must use” plugins are like ordinary plugins but ran earlier in the WordPress loop and always enabled. Not sure how to create a “must use” plugin? See How to create a “Must-Use” plugin.

if ( isset( $_SERVER["HTTP_CF_CONNECTING_IP"] ) ) {
 $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
}

Was this article helpful?

Related Articles