Getting A ClientPC’s Real IP Address Using PHP
Getting a client’s IP address can be quite simple as using $_SERVER[‘REMOTE_ADDR’], but the only thing is once the client uses a Proxy Server to connect to the Internet, it won’t return its real IP address anymore. Instead, it will return the IP address of the proxy server and not the client’s machine itself.
So if you want to avoid that from happening, you can use this nifty PHP function shared by laeeq of PHPzag.
function getRealIpAddress() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip=$_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip=$_SERVER['REMOTE_ADDR']; } return $ip; }
In the above function, $_SERVER[‘HTTP_CLIENT_IP’] server variable is primarily used to get the client machine’s direct IP address. If it’s not available then it moves on using HTTP_X_FORWARDED_FOR. If it still doesn’t find any then it’ll try using REMOTE_ADDR.