DEV Community


An easy way to get the (real) client IP in PHP

Rogerio Taques
Solo maker of, & Helping localize the Internet at Occasionally writing on, Medium and at!
・1 min read

Here we go with another post! 🀘

In the other day I noticed all IPs recorded from visitor on one of my apps were the same, with a very little variation each-other! Aha~ found a bug!

Well, not much! πŸ™„ After a quick Google search I figured out that those IPs were all from CloudFlare (the CDN provider my apps are behind)! So, CloudFlare replaces the commonly used $_SERVER['REMOTE_ADDR'] variable with their own IP.

Fair enough!

So, if you're reading this, the chances are you are facing a similar problem and are looking for a solution ... or perhaps you're just curious, which is fine too. πŸ€ͺ

Here's a very simple way to get the (real) client IP address. Note that the sintax used here is PHP7+, which means for earlier versions you're gonna need to apply some chained ifs and elses.


# PHP7+
    ?? $_SERVER["HTTP_CF_CONNECTING_IP"] # when behind cloudflare
    ?? '';

# Earlier than PHP7
$clientIP = '';

if (isset($_SERVER['HTTP_CLIENT_IP'])) {
    $clientIP = $_SERVER['HTTP_CLIENT_IP'];
} elseif (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
    # when behind cloudflare
} elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
} elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
    $clientIP = $_SERVER['HTTP_X_FORWARDED'];
} elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
} elseif (isset($_SERVER['HTTP_FORWARDED'])) {
    $clientIP = $_SERVER['HTTP_FORWARDED'];
} elseif (isset($_SERVER['REMOTE_ADDR'])) {
    $clientIP = $_SERVER['REMOTE_ADDR'];

echo "My client IP: ", $clientIP;

Enter fullscreen mode Exit fullscreen mode

Happy coding! πŸ‘‹

Discussion (4)

arvin profile image

Good post Rogerio :)

I also had to unmask the real IP when I started using Cloudflare.
Since my projects were hosted on my own server and it was more than one project, I decided to use mod_remoteip instead of tweaking the code everywhere, and already get the real IP when I’m using $_SERVER[β€˜REMOTE_ADDR’].

More on this for those who are in the same situation:

rogeriotaques profile image
Rogerio Taques Author

That’s an awesome solution, Arvin! Thanks for sharing. πŸ™πŸ‘πŸ€©

rileyjones profile image
Riley Jones

I had the same problem. I used the "REMOTE_ADDR" method on my website and it was showing up my cloudflare ip address. I wanted to echo the users ip, so this answer helped me out a ton. I had to create an account just to applaud you. Great job!

jboada profile image

Hi Rogerio,

Awesome solution!