|  | Posted by Aaron Saray on 09/09/07 14:14 
On Sep 8, 11:04 am, "J.O. Aho" <u...@example.net> wrote:> Rob wrote:
 > > Just wondering how sites capture a visitor's IP address and how this is
 > > done in PHP?
 >
 > There is a page which lists PHP global variables, these are useful to know,http://www.php.net/manual/en/reserved.variables.php
 >
 > As you see $_SERVER['REMOTE_ADDR'] will hold the remote users IP-address (if
 > the remote user is using a proxy, then it's the proxy IP-address you get).
 >
 > So in your code you can use:
 >
 > <?PHP
 > $userip=$_SERVER['REMOTE_ADDR'];
 >
 > echo "This is your ip-number: {$userip}<br>";
 >
 > //File we want to store the ip-number to
 > //se to have this file already.
 > $filename = 'storeipnumbers.txt';
 > if (is_writable($filename)) {
 >   if (!$handle = fopen($filename, 'a')) {
 >      echo "Cannot open file ($filename)";
 >      exit;
 >   }
 >   if (fwrite($handle, $userip) === FALSE) {
 >     echo "Cannot write to file ($filename)";
 >     exit;
 >   }
 >   fclose($handle);
 >   echo "We have stored ip-number '{$userip}' to file '{$filename}'";} else {
 >
 >   echo "Sorry, we couldn't store the following ip-number: {$userip}<br>";}
 >
 > ?>
 >
 > This script displays the ip-number and stores it to a file called
 > storeipnumbers.txt.
 > --
 >
 >   //Aho
 
 Users can also have a proxied IP address.  This is what I use to
 figure out the IP addresses (its from a class - hence $this):
 
 /**
 * Get user ip
 *
 * Get user's ip and also proxy if it exists.
 */
 protected function _getIP()
 {
 
 /**
 * Check for http forwarding proxy
 */
 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) || !
 empty($_SERVER['HTTP_CLIENT_IP'])) {
 
 /**
 * REMOTE_ADDR would be the proxy IP
 */
 if (!empty($_SERVER['REMOTE_ADDR'])) {
 $this->_proxyIP = $_SERVER['REMOTE_ADDR'];
 }
 
 /**
 * HTTP_X_FORWARDED_FOR would be the user's ip.
 */
 if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) &&
 empty($_SERVER['HTTP_CLIENT_IP'])) {
 
 /**
 * not set, so set our user ip to our proxy's ip as
 well (or all NULL even)
 */
 $this->_userIP = $this->_proxyIP;
 }
 
 /**
 * get our proxy ip
 */
 elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
 $this->_userIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
 }
 elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {
 $this->_userIP = $_SERVER['HTTP_CLIENT_IP'];
 }
 }
 
 /**
 * not proxied
 */
 else {
 
 /**
 * if we can detect ip
 */
 if (isset($_SERVER['REMOTE_ADDR'])) {
 $this->_userIP = $_SERVER['REMOTE_ADDR'];
 }
 }
 }
  Navigation: [Reply to this message] |