Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / PHP

Get IP Address using PHP

5.00/5 (1 vote)
8 Oct 2012CPOL1 min read 51.9K  
This post shows you how to get user's IP address using PHP.

Introduction

Nowadays, getting a visitor's IP address is very important for many reasons. These reasons can include logging, targeting, redirecting, etc. IP information can be found in the $_SERVER array. The easiest way to get the visitor's IP address is by reading the REMOTE_ADDR field within this $_SERVER array. The following example illustrates how easy it is:

PHP
<?php $ip = $_SERVER['REMOTE_ADDR']; ?>

This solution, however, is not entirely accurate due to proxy applications that users may have, meaning that you will get the IP of the proxy server and not the real user address. Luckily, PHP gives us a few more indices to get more accurate results. Proxy servers extend the HTTP header with new property which stores the original IP. In order to be more accurate with your reading, you would need to verify all three of the following indices (including the first one I gave above). The other two are the following:

PHP
<?php 
    $remote = $_SERVER['REMOTE_ADDR'];

    $forwarded = $_SERVER['HTTP_X_FORWARDED_FOR'];

    $client_ip = $_SERVER['HTTP_CLIENT_IP'];
?>

Now that we know how to get the IP address from a user, then we can go ahead and create a reusable function that will indeed return an IP address if it is present, or return false otherwise:

PHP
<?php 
    function getIp(){

        $ip = $_SERVER['REMOTE_ADDR'];     
        if($ip){
            if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
            }
            return $ip;
        }
        // There might not be any data
        return false;
    }
?>

Note: Even with more Indices to play around with, it does not mean that this will still be 100% accurate. It is easy to manipulate these values using browser plug-ins to change header information, proxy applications or even proxy websites. Because of this, I recommend you use more information from the user, such as MAC address and the use of cookies.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)