PHP – Get a visitor’s IP address

/**
 * This function tries to get the real IP of the visitor even if they 
 * are behind a proxy
 */
function getClientIp()
{
    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;
}

Posted

in

by

Comments

2 responses to “PHP – Get a visitor’s IP address”

  1. Alfred Ayache Avatar

    Hi Moazzam:

    You have some cool stuff on your blog. Thanks for sharing.

    I think you have a spurious lowercase s on line 9 of your listing here:

    } elseif (!empty($_SERVER[‘HTTP_X_sFORWARDED_FOR’])) {

    Should be:

    } elseif (!empty($_SERVER[‘HTTP_X_FORWARDED_FOR’])) {

    HTH,
    – AAA

  2. Moazzam Avatar

    Thanks for pointing that out. I corrected the spelling mistake

Leave a Reply

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