Detect visitor IP address with PHP

Two post in 2 days… 🙂

Here is a small PHP function to detect remote IP address (visitor IP address). This should work even if the client/visitor is behind a proxy

function getIPAddress() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
      $ip = $_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
      $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else {
      $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
 
$ip = getIPAddress();
echo $ip;

There is not much to talk about. As you can see, the $ip variable is detected IP address.

Leave a Reply

Your email address will not be published. Required fields are marked *