Different ways to get an IP address in PHP with Cloudflare, internal proxy, and more

Tiempo de lectura: 2 minutos

We will learn how to get the IP address in PHP even if our server is masked from Cloudflare, Nginx Proxy or not using any type of proxy.

Breakfast - pexels

We will first create a new PHP file called ip_config.php

To get the IP address we will use the following function:

<?php function getIP(): string { if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) { $ip = $_SERVER['HTTP_CF_CONNECTING_IP']; // Real IP address of the client behind Cloudflare } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { // May contain multiple IPs, take the first valid one $ipList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); $ip = trim($ipList[0]); } elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } else { $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'; } return $ip; } 

And now I’ll explain what each block does:

if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) { $ip = $_SERVER['HTTP_CF_CONNECTING_IP']; } 

This header is added by Cloudflare when your server is behind their network.

if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ipList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); $ip = trim($ipList[0]); } 

Used by reverse proxies, load balancers or CDN (not always Cloudflare).

if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } 

<

p Less common, but some proxies or internal networks use it to indicate the client’s IP address.

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

This is the default value, the client’s IP address that connects directly to the server.

Scenario Header used Reliability
Cloudflare HTTP_CF_CONNECTING_IP High
Proxy / Load Balancer HTTP_X_FORWARDED_FOR Moderate
Direct Client REMOTE_ADDR High

If we have an internal proxy like Nginx Proxy Manager, we’ll need to put the following:

# Trust Cloudflare's IP ranges set_real_ip_from 103.21.244.0/22; set_real_ip_from 103.22.200.0/22; set_real_ip_from 103.31.4.0/22; set_real_ip_from 104.16.0.0/13; set_real_ip_from 104.24.0.0/14; set_real_ip_from 108.162.192.0/18; set_real_ip_from 131.0.72.0/22; set_real_ip_from 141.101.64.0/18; set_real_ip_from 162.158.0.0/15; set_real_ip_from 172.64.0.0/13; set_real_ip_from 173.245.48.0/20; set_real_ip_from 188.114.96.0/20; set_real_ip_from 190.93.240.0/20; set_real_ip_from 197.234.240.0/22; set_real_ip_from 198.41.128.0/17; real_ip_header CF-Connecting-IP; real_ip_recursive on; # Optional: also forward the IP in headers for PHP proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 

Leave a Comment