Get correct IP address using PHP

This tutorial will show you how you can correct IP address of a user who is visiting your website.

If you work on PHP applications; sooner or later you are going to need to get the end user’s IP address. We use to get the IP address using get $_SERVER[‘REMOTE_ADDR’].

Today it is not so easy to get the actual IP address. For both performance and security reasons many web servers put some sort of proxy in front of the web server which means that if you are using a load balancer or CloudFlare then $_SERVER[‘REMOTE_ADDR’] will only return the IP address of the proxy, not the IP address of the user accessing your site.

Fortunately there is a way around this using the X-Forwarded-For header. This is a server header set by the proxy to pass through the IP address of the end user where necessary. Therefore, while REMOTE_ADDR still exists the X-Forwarded-For header is the one that is actually tied to the user’s actual IP address.


PHP 5.4
MySQL 5.5
Apace http Server 2.4
Netbeans 7.4 (Optional)

Step 1. Creates a php projects using Netbeans or create a project directory under htdocs.

Step 2. Create below function to get correct IP address of a user

//get IP Address
function get_real_ip_address() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {   
        //check ip from shared internet
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {   
        //to check ip is pass from proxy
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        //REMOTE_ADDR if neither of above is available
        $ip = $_SERVER['REMOTE_ADDR'];
    return $ip;

That’s all. Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *