Some times we need the visitor’s IP address for validation, security, spam prevention etc. Getting the Visitor’s IP address is very easy in PHP.
We can get the Internet Protocol (IP) address of any visitor by using PHP.
The easy way to get the visitor’s IP address in php is :
1 2 3 4 |
// Get the visitors ip address <?php echo $ipaddress = $_SERVER['REMOTE_ADDR']; ?> |
Some times this does not returns the correct IP address of the visitor. This may happen due to reasons like the user is behind a proxy, your apache server is behind a reverse proxy (e.g. varnish) etc.
So we can use some other server variables to get the ipaddress.
Proxy Server Address
Some visitors browse from behind proxy servers. We can collect the address of proxy along with the IP address of client by using this code.
Other Server variables
$_SERVER is an array and it contains lot of information as supplied by server and one of the element is ‘REMOTE_ADDR’ which gives us the IP address.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function get-real-ip-address() { 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; } |