Get The IP Address Of A Visitor Through PHP

I have talked previously about getting an IP address of a visitor with PHP. The failing in using the value of $_SERVER["REMOTE_ADDR"] is that if the visitor is using a proxy then you will get the proxy IP address and not the visitors real IP address.

This function works by going through any variables in the $_SERVER array that might exist that would contain information to do with IP addresses. If they are all empty then the function finally looks at $_SERVER["REMOTE_ADDR"] value and returns this as a default.

function getRealIpAddr(){
 if ( !empty($_SERVER['HTTP_CLIENT_IP']) ) {
  // Check IP from internet.
  $ip = $_SERVER['HTTP_CLIENT_IP'];
 } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
  // Check IP is passed from proxy.
  $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
 } else {
  // Get IP address from remote address.
  $ip = $_SERVER['REMOTE_ADDR'];
 }
 return $ip;
}

To run this function just call it.

echo getRealIpAddr();

 

Comments

Hi, I have go through this post and found very helpful but i still could not able to found the real ip. I use geoip api to track the country but when i get the ip from given function it could not return country and if i try http://www.whatismyip.com ip address it return the country correctly. thanks, akram.
Permalink
This technique is most important when you want to check from where your site is accessing or what is your behavior of your website visitor. If something wrong happen by any person meas if they doing some vulnerable activities then you can easily block that visitor. Thanks for such nice code which help people to get IP address of particular user.
Permalink

Hi, How can I get the URLs and page title of a visitor through PHP...

Thanks in advance.

Permalink

Please note: A user can specify whatever they like for 'X-Forwarded-For' so could claim to be from whatever source IP they want,

its true some proxy servers will put the real IP here, but you can really put whatever you want there (even something thats not even an IP Address..)

Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
1 + 16 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.