It is very common that websites are retrieving the user’s IP address to implement access controls of users or visitors in PHP.The REMOTE_ADDR field in $_SERVER superglobal is normally held the user’s true IP address.But sometimes user uses proxy Server to hide own IP Address and try to access website by hiding behind proxies and at that time $_SERVER[‘REMOTE_ADDR’] returns the IP address of the proxy server not the user’s machine IP Address in PHP.
So. Here I am going to share function which will provide the real IP address of visitors machine even they are using a proxy server.
The HTTP_X_FORWARDED_FOR field contains the IP Address of the user if they are using Proxy Server.
Read about: Exception handling in PHP5
There is 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
Function to find real IP address in PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | function getRealIP() { $headers = array ('HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'HTTP_VIA', 'HTTP_X_COMING_FROM', 'HTTP_COMING_FROM', 'HTTP_CLIENT_IP' ); if (isset ( $_SERVER [$header] )) { if (($pos = strpos ( $_SERVER [$header], ',' )) != false) { $ip = substr ( $_SERVER [$header], 0, $pos ); } else { $ip = $_SERVER [$header]; } $ipnum = ip2long ( $ip ); if ($ipnum !== - 1 && $ipnum !== false && (long2ip ( $ipnum ) === $ip)) { if (($ipnum - 184549375) && // Not in 10.0.0.0/8 ($ipnum - 1407188993) && // Not in 172.16.0.0/12 ($ipnum - 1062666241)) // Not in 192.168.0.0/16 if (($pos = strpos ( $_SERVER [$header], ',' )) != false) { $ip = substr ( $_SERVER [$header], 0, $pos ); } else { $ip = $_SERVER [$header]; } return $ip; } } } return $_SERVER ['REMOTE_ADDR']; } |
Explanation
This function will first try to get the direct IP address of user machine.if fail to get then it will check for proxy server address using HTTP_X_FORWARDED_FOR and using some other headers.The HTTP_X_FORWARDED_FOR field is supported by most proxy servers to identify the IP address of the host which is requesting from the HTTP request through the proxy server and if everything gets fails, then finally get the IP address using REMOTE_ADDR.
I hope that you find above code useful! You can use this code anywhere you want. Did we miss anything? Tell me in the comment section :).
Comments (23)