Getting Visitor IP Address in PHP



Some times we need to get visitor’s ip address for validation, security, spam prevention etc. In php it’s easy to get visitor ip address.

No Proxy detection
If there is no proxy detection we can get the visitor ip address with a simplest way as follow:

$ip = $_SERVER['REMOTE_ADDR']; 

But If a user access the website via a proxy server $_SERVER[‘REMOTE_ADDR’] will return the ip address of proxy server not of the proxy user. So we have two methods here to get the ip address of a user.

Using $_SERVER
$_SERVER is an array created by the web server, that contains the server variables.

function get_visitor_ip() {
    $ip = '';
    if ($_SERVER['HTTP_CLIENT_IP'])
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    else if($_SERVER['HTTP_X_FORWARDED_FOR'])
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if($_SERVER['HTTP_X_FORWARDED'])
        $ip = $_SERVER['HTTP_X_FORWARDED'];
    else if($_SERVER['HTTP_FORWARDED_FOR'])
        $ip = $_SERVER['HTTP_FORWARDED_FOR'];
    else if($_SERVER['HTTP_FORWARDED'])
        $ip = $_SERVER['HTTP_FORWARDED'];
    else if($_SERVER['REMOTE_ADDR'])
        $ip = $_SERVER['REMOTE_ADDR'];
    else
        $ip = 'none';
 
    return $ip;
}

Using getenv() function
getenv() function is used to read the value of the environment variables in PHP. This function is useful when visitors are using the proxy server to access the site.

function get_visitor_ip()  {
    $ip = '';
    if (getenv('HTTP_CLIENT_IP'))
        $ip = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $ip = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $ip = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
        $ip = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $ip = getenv('REMOTE_ADDR');
    else
        $ip = 'none';
 
    return $ip;
}

You can use any method from above to get visitor ip address. These will work only on live site.

demo

Get Visitor IP Address
Get Visitor IP Address