Most of us should be relying on the server side environmental variable REMOTE_ADDR solely for client IP addresses
Yet it’s barely enough to get the real IP for a variety of circumstances such as when the user is visiting your website from a proxy server. To everyone’s surprise, there are a lot more environmental variables regarding client IP address than just the most straightforward one, REMOTE_ADDR. Consider this snippet in the attempt to detect the real source IP address of the request:
function get_ip_address() {
foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key) {
if (array_key_exists($key, $_SERVER) === true) {
foreach (explode(',', $_SERVER[$key]) as $ip) {
if (filter_var($ip, FILTER_VALIDATE_IP) !== false) {
return $ip;
}
}
}
}
}
'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED', 'REMOTE_ADDR'
these are
possible environmental variables that may contain the client
IP address. You better not change the order these variable names are
placed in the literal array.
We are using this approach because
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.
In other way we can write like this
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
PHP Functions available to detect IP address
PHP function - $REMOTE_ADDR |
PHP function - $REMOTE_HOST |
PHP function - $HTTP_X_FORWARDED_FOR |
PHP function - $HTTP_VIA |
PHP function - $HTTP_CLIENT_IP |
PHP function - $HTTP_PROXY_CONNECTION |
PHP function - $FORWARDED_FOR |
PHP function - $X_FORWARDED_FOR |
PHP function - $X_HTTP_FORWARDED_FOR |
PHP function - $HTTP_FORWARDED |
No comments:
Post a Comment