William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

PHP: get IP address

1. http://whatismyip.com

The easiest way to find our real IP is from the url: http://whatismyip.com/.
It return the computer’s Internet address.

2. PHP: get IP Address

According to PHP’s office page,$_SERVER[‘REMOTE_ADDR’] return ‘The IP address from which the user is viewing the current page’.

Do you use $_SERVER[‘REMOTE_ADDR’] to find client’s IP address in PHP? Well, you might be amazed to know that it may not return the true IP address of the client at all time.

If client connects to the Internet through Proxy Server, then $_SERVER[‘REMOTE_ADDR’] in PHP just returns the IP address of the proxy server, not the client’s machine.

Actually, there are 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 and HTTP_X_FORWARDED_FOR.

The following is a simple function I got from web to find real client’s IP address:

function get_real_ip_addr() {
 //check ip from share Internet
 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
  $ip=$_SERVER['HTTP_CLIENT_IP'];
 }
 //check ip is pass from proxy
 elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
 }
 else{
  $ip=$_SERVER['REMOTE_ADDR'];
 }
 return $ip;
}

It first attempts to get direct IP address of client’s machine; if not, then try for forwarded for IP address using HTTP_X_FORWARDED_FOR. And if this is also not available, then finally get the IP address using REMOTE_ADDR.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: