Getting real IP address in PHP

Are you using $_SERVER[‘REMOTE_ADDR’] to find the the client’s IP address in PHP? Well dude, you might be amazed to know that it may not return the true IP address of the client at all time. If your client is connected to the Internet through Proxy Server then $_SERVER[‘REMOTE_ADDR’] in PHP just returns the the IP address of the proxy server not of the client’s machine.  So here is a simple function in PHP to find the real IP address of the client’s machine. There are extra Server variable which might be available to determine the exact IP address of the client’s machine in PHP, they are HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR.

Function to find real IP address in PHP

function getRealIpAddr()
{
if (!empty($_SERVER[‘HTTP_CLIENT_IP’]))
//check ip from share 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
{
$ip=$_SERVER[‘REMOTE_ADDR’];
}
return $ip;
}

In this PHP function, first attempt is to get the direct IP address of client’s machine, if not available then try for forwarded for IP address using HTTP_X_FORWARDED_FOR. And if this is also not available, then finally get the IP address using REMOTE_ADDR.

Getting real IP address in PHP: 1 комментарий

  1. valik

    There are much more headers that you can check if someone is using proxy. Thes is what I know:
    HTTP_PRAGMA, HTTP_XONNECTION, HTTP_CACHE_INFO, HTTP_XPROXY, HTTP_PROXY, HTTP_PROXY_CONNECTION, HTTP_CLIENT_IP, HTTP_VIA, HTTP_X_COMING_FROM, HTTP_X_FORWARDED_FOR, HTTP_X_FORWARDED, HTTP_COMING_FROM, HTTP_FORWARDED_FOR, HTTP_FORWARDED, ZHTTP_CACHE_CONTROL

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *