Categories
PHP

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;
}

By Moazzam

Moazzam is a software developer working in the big apple. He has over a decade of experience in development. While most of his work involves developing web applications, he does development for Android and Windows Mobile in his spare time.

2 replies on “PHP – Get a visitor’s IP address”

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

Leave a Reply

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