How to get the client's IP address?

You know that. You want (or need) to log some user activity and his/her IP address is very often one of the most requested values.


The most reliable value you can get is in system variable $_SERVER['REMOTE_ADDR'].
However, the user can be behind a proxy server and it may have set the $_SERVER['HTTP_X_FORWARDED_FOR'] variable. But be aware, this value is easily spoofed!
So, if you are going to save the $_SERVER['HTTP_X_FORWARDED_FOR'], make sure you save the value from the $_SERVER['REMOTE_ADDR'] variable too.
But sometimes you can find other server variables with the IP address (e.g. from shared internet etc.). Other possibilities are: 'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED', HTTP_X_FORWARDED_FOR', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED'
Anyway you should validate the IP address every time. For the validation you can use a filter_var php function.
How to get and validate user's IP? See an example of these functions:
function isValidIPAddress($ipAddress){
 if (filter_var($ipAddress, FILTER_VALIDATE_IP,
   FILTER_FLAG_IPV4 |
   FILTER_FLAG_NO_PRIV_RANGE |
   FILTER_FLAG_NO_RES_RANGE) === false)
  return false;
 return true;
}

function getIPAddress() {
 $possibilities = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR',
                         'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP',
                         'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED',
                         'REMOTE_ADDR');
 foreach ($possibilities as $key) {
  if (array_key_exists($key, $_SERVER) === true) {
   foreach (explode(',', $_SERVER[$key]) as $ipAddress) {
    $ipAddress = trim($ipAddress);
    if (isValidIPAddress($ipAddress)) {
     return $ipAddress;
    }
   }
  }
 }
 return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : false;
}

Comments