
Finding visitors real IP using PHP
Third PHP snippet I’m sharing from my library is code that tries to get most accurate real IP of the visitor. There are few headers with the IP information but those can be populated with many different ip’s based on customers route to your server. This script evolved in time and I believe it returns a very accurate source IP based on the information given in the request headers. But if you find a bug or a way to enhance it more, let me know!
License
This code is free to use, distribute, modify and study. When referencing please link back to this website / post in any way e.g. direct link, credits etc. If you find this useful, please leave a comment and share using the buttons below!
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 31 32 33 34 35 |
<?php function realip() { $ip = trim($_SERVER['REMOTE_ADDR']); if ($_SERVER["HTTP_CLIENT_IP"]) { if (preg_match("~\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}~", trim($_SERVER["HTTP_CLIENT_IP"])) && !preg_match("~^((0|10|127|169\.254|172\.(1[6-9]|2[0-9]|3[0-1])|192\.0\.2|192\.168|255\.255\.255)\.)~", trim($_SERVER["HTTP_CLIENT_IP"]))) { $ip = trim($_SERVER["HTTP_CLIENT_IP"]); } } elseif ($_SERVER["HTTP_X_FORWARDED_FOR"]) { foreach (explode(",", $_SERVER["HTTP_X_FORWARDED_FOR"]) as $key) { if (preg_match("~\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}~", trim($key)) && !preg_match("~^((0|10|127|169\.254|172\.(1[6-9]|2[0-9]|3[0-1])|192\.0\.2|192\.168|255\.255\.255)\.)~", trim($key))) { $ip = trim($key); break; } } } return ($ip); } $IP = realip(); ?> |