PHP: Get the correct IP address from a Cloudflare request.

If your PHP application is behind Cloudflare, then you will need to modify your code to retrieve the user’s correct IP address. This is because REMOTE_ADDR will be the IP address of the Cloudflare server that handled the request.

Getting the CF-Connecting-IP in PHP.

Fortunately, Cloudflare will forward us the client’s correct IP address using the Cf-Connecting-IP header. In PHP, this will be available in the $_SERVER superglobals array as HTTP_CF_CONNECTING_IP.

An example:

Unfortunately, the code above assumes that our PHP application will always be sitting behind the Cloudflare service. This won’t always be the case, as Cloudflare can be disabled for debugging purposes and you will also need to be able to run your website on a local testing environment. You also don’t want your application to break if you decide to stop using Cloudflare altogether.

The fix for this is simple:

The PHP code above checks to see if the CF-Connecting-IP header exists. If it does, it assumes that the application is sitting behind the Cloudflare server. If it doesn’t, it uses the normal way of retrieving a visitor’s IP address.

CF-Connecting-IP spoofing.

Like most headers, the CF-Connecting-IP header can be spoofed. This means that a visitor could manually add the CF-Connecting-IP header and fool your application into thinking that the request came via Cloudflare. If they can do this, then they can give your PHP application any IP address that they want to.

To guard against this, you will need to validate the REMOTE_ADDR IP address. If the request came through Cloudflare, then the REMOTE_ADDR $_SERVER variable should contain an IP address that belongs to Cloudflare.

Fortunately, Cloudflare has a page that lists their IP ranges. This list of IP ranges is extremely useful, as it allows us to validate the IP address and make sure that the request came from their service.

An example where we validate that the request came from Cloudflare before accepting the CF-Connecting-IP header:

Note: The ip_in_range function belongs to Joomla and can be found here.

Hopefully, you found this post useful!

Facebook Comments