Simplify your business
Friday, 29 August 2008 9:25 am

Getting the client IP address

Tuesday, 5 June 2007  

We’ve seen plenty of PHP scripts that rely on the $_SERVER['REMOTE_ADDR'] variable when trying to establish the IP address of the client computer. The problem with this approach is that if your visitor is behind a corporate firewall or proxy, then the above will actually be the IP of the firewall or proxy, not the visitors computer.

This function pretty much caters for all situations:

function getip() {
   if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
      $result = $_SERVER['HTTP_X_FORWARDED_FOR'];
   } elseif (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
      $result = $_SERVER['HTTP_CLIENT_IP'];
   } else {
      $result = $_SERVER['REMOTE_ADDR'];
   }
   if (strstr($result, ',')) {
      $result = strtok($result, ',');
   }
   return $result;
}

Just keep in mind that $_SERVER['REMOTE_ADDR'] can be (and has been) spoofed.

Posted in PHP, Tips by Ivan
Blinklist icon Del.iocio.us icon Furl icon Reddit icon Technorati icon Yahoo! icon

 one comment:

  1. Guru - Thursday, 22 November 2007 11:25 pm  

    Hi,

    We are in the requirement that we need to get the IP address (local machine's). We are getting the general IP address of the provider and not the network inside it. Meaning we are getting the same IP address in all machines in our office. As per the suggestion given by you in this site, we have tried your example, but still we are getting the same as IP address. Can we get suggestions over it?

    Regards, Guru


Got something to say?

To protect your privacy, your email address will not be displayed.





Some basic rules for commenting:

  • Watch your language.
  • Keep comments on-topic and relevant.
  • You can use basic XHTML tags for formatting and linking but not bbcode.
  • Comments are moderated, so don't double post if your comment doesn't appear immediately.
  • Please proof-read your comments for spelling and grammar mistakes.
  • Watch your language.