Getting real IP address in PHP


 / Published in: PHP
 

URL: http://snipplr.com/extras/

Are you using $SERVER['REMOTEADDR'] to find the the client's IP address? Well dude, you might be amazed to know that it may not return the true IP address of the client at all time. If your client is connected to the Internet through Proxy Server then $SERVER['REMOTEADDR'] just returns the the IP address of the proxy server not of the client's machine. So here is a simple function in PHP to find the real IP address of the client's machine.

  1. function getRealIpAddr()
  2. {
  3. if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
  4. {
  5. $ip=$_SERVER['HTTP_CLIENT_IP'];
  6. }
  7. elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
  8. //to check ip is pass from proxy
  9. {
  10. $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
  11. }
  12. else
  13. {
  14. $ip=$_SERVER['REMOTE_ADDR'];
  15. }
  16. return $ip;
  17. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: arkin on January 3, 2008

This is not a secure way of getting the real ip address. This is how IP forgery can happen because the first 2 are passed in a users headers.

Posted By: kdaviesnz on January 14, 2008

One line alternative: $ip = !empty($SERVER['HTTPCLIENTIP'])?$SERVER['HTTPCLIENTIP']:(!empty($SERVER['HTTPXFORWARDEDFOR'])?$SERVER['HTTPXFORWARDEDFOR']:$SERVER['REMOTEADDR']);

Posted By: section31 on July 6, 2008

Agreed, it's very rare that you need to get their forwarded ip.

Posted By: nightowl on June 11, 2009

Wrong, in South Africa all ISP's send their clients via a transparent proxies due to the high cost of bandwidth. (A transparent proxy mean the user never have to set up the proxy server settings in their browser, all traffic is forwarded to the proxy server and then to the internet)

I presume that a lot of ISP's in smaller countries do the same

You need to login to post a comment.