- Instant help with your Php coding problems

Get visitors IP address with PHP

Getting a visitor's IP address can be important for a lot of reasons, for example, logging, geo-targeting, redirecting the user, and so on. All of the IP relevant information can be found in the $_SERVER  array. The simplest way to get the visitors IP address is as simple as the following code, by reading the REMOTE_ADDR  field:

$ip = $_SERVER['REMOTE_ADDR'];

However, this solution is not completely accurate, as if the user sits behind a proxy, then you will get the IP of the proxy server and not the real user address. Fortunately, we can make some additional refinement to get more accurate results. Proxy servers extend the HTTP header with a new property that stores the original IP. The name of this field is X-Forwarded-For  or Client-Ip . If one of these fields is present in the HTTP header then you can read their values from the $_SERVER array as in the first example. So you need to check all the 3 possibilities:

echo "Remote addr: " . $_SERVER['REMOTE_ADDR']."<br/>";
echo "X Forward: " . $_SERVER['HTTP_X_FORWARDED_FOR']."<br/>";
echo "Clien IP: " . $_SERVER['HTTP_CLIENT_IP']."<br/>";

Using this information is quite easy now to create a simple function that returns the probably real IP of the site visitor:

function getIp() {
    $ip = $_SERVER['REMOTE_ADDR'];
 
    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;
}

Note: Why I wrote, “probably real”? Because the values of the X-Forwarded-For and Client-Ip are not reliable. It is quite easy to manipulate these values. For example, simply installing a Firefox plugin to change header information. Because of this don’t use this IP alone for security purposes.

Share "Get visitors IP address with PHP" with your friends