Pawan Kumawat

How To Get the client IP address using PHP

You want to know your site is access by which IP address.  If yes than this blog will help you so much.

Sometimes for security reasons we need to know IP address of our site’s user.

Simplest way is using $_SERVER['REMOTE_ADDR'] or $_SERVER['REMOTE_HOST'] variables . but sometimes  it don’t return correct IP address. so for this getenv() is used to get the value of an environment variable in PHP.

For this we have 4-5 method  but we will include it in 1 function only –

function getUserIP()
    $ipaddress = '';
    if (getenv('HTTP_CLIENT_IP')) $ipaddress = getenv('HTTP_CLIENT_IP');
    else if (getenv('HTTP_X_FORWARDED_FOR')) $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
    else if (getenv('HTTP_X_FORWARDED')) $ipaddress = getenv('HTTP_X_FORWARDED');
    else if (getenv('HTTP_FORWARDED_FOR')) $ipaddress = getenv('HTTP_FORWARDED_FOR');
    else if (getenv('HTTP_FORWARDED')) $ipaddress = getenv('HTTP_FORWARDED');
    else if (getenv('REMOTE_ADDR')) $ipaddress = getenv('REMOTE_ADDR');
    else $ipaddress = 'UNKNOWN';
    return $ipaddress;


Share This On :

Leave a Comment

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

Scroll to Top

Request A Quote