faqts : Computers : Programming : Languages : PHP : Common Problems : Visitor Information

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

379 of 458 people (83%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How can I get the IP address of a visitor?
How can I get the domain name of a visiting client browser?
What is the REMOTE_ADDR?

Jun 1st, 2002 21:03
Philip Olson, Nathan Wallace, John Coggeshall, Rod, Sascha Schumann


PHP makes REMOTE_ADDR and REMOTE_HOST available for our use, they live
within the SERVER arrays.  So:
  REMOTE_ADDR - the IP address of the client
  REMOTE_HOST - the host address of the client, if available
  http://www.php.net/manual/en/language.variables.predefined.php
Example:
  // Has worked since PHP 3
  print $HTTP_SERVER_VARS['REMOTE_ADDR'];
  // Has worked since PHP 4.1.0
  print $_SERVER['REMOTE_ADDR'];
You may also use the getenv function, see:
  http://www.php.net/getenv
To see other predefined variables and information, make a call to 
phpinfo() and call it:
  <?php phpinfo(); ?>
That will show you all of the environment variables that are available
within your scripts.
If your server doesn't look up the host name of the client 
automatically then gethostbyaddr() might be useful.  Many servers are
setup to not lookup the host name automatically as it wastes resources.
 See:
  http://www.php.net/gethostbyaddr
Example:
  $host = gethostbyaddr($HTTP_SERVER_VARS['REMOTE_ADDR']);
Sometimes you may get the IP of the ISP Cache Server which you may not
want.  To help, check for HTTP_X_FORWARDED_FOR:
  <?php
    if (getenv(HTTP_X_FORWARDED_FOR)) {
      $ip   = getenv('HTTP_X_FORWARD_FOR');
      $host = gethostbyaddr($ip);
    } else {
      $ip   = getenv('REMOTE_ADDR');
      $host = gethostbyaddr($ip);
   }
  ?>
Note that if the PHP directive register_globals is enabled, PHP will
also make $REMOTE_ADDR available.  As of PHP 4.2.0 this directive
defaults to off.  Going through a SERVER variable will always work.