Full Stack LAMP - MEAN Developer, Python developer. Certified Azure Developer. Freelance programmer/consultant/trainer.

How to get Real IP from Visitor?

Today’s Post is about Getting Visitor’s Real IP Address Using PHP, you can get visitor IP with the help of server Environment Variables in PHP.

we can easily get visitor’s ip address with $_SERVER['REMOTE_ADDR'] or $_SERVER['REMOTE_HOST'] Variables.

$_SERVER[‘REMOTE_ADDR’] is the only reliable IP address you’ll get – it’s extracted directly from the TCP stack and is where the current connection was established from. This means if the user is connecting via a proxy, you’ll get the proxy’s address, not the user’s.

So we can’t trust the result of above variables, So In order to get the real correct ip address we have to use some other server variables.

function get_client_ip() {
     if ($_SERVER['HTTP_CLIENT_IP'])
         $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
     else if($_SERVER['HTTP_X_FORWARDED_FOR'])
         $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
     else if($_SERVER['HTTP_X_FORWARDED'])
         $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
     else if($_SERVER['HTTP_FORWARDED_FOR'])
         $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
     else if($_SERVER['HTTP_FORWARDED'])
         $ipaddress = $_SERVER['HTTP_FORWARDED'];
     else if($_SERVER['REMOTE_ADDR'])
         $ipaddress = $_SERVER['REMOTE_ADDR'];
         $ipaddress = 'UNKNOWN';

     return $ipaddress; 

Note: HTTP_X_FORWARDED_FOR sometimes returns internal or local IP address, which is not usually useful. Also, it would return a comma separated list if it was forwarded from multiple ipaddresses.

$_SERVER is an array contains server variables created by the web server.

Leave a Reply