How can I get the Machine IP of visitors of my website logged.

I've used

function getIp(){

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

BUt what I get is my server IP.

Thanks

Recommended Answers

@Masterblank That could be simplified a lot and improved.

function getIp($ifNull = "") { # allow specification of null value
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
    }

    return $_SERVER['REMOTE_ADDR'] ? $_SERVER['REMOTE_ADDR'] : $ifNull;
}

getIp("127.0.0.1");
>> IP or 127.0.0.1 if it can't …
Jump to Post

All 2 Replies

function getIp(){ 

    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'] ? $_SERVER['REMOTE_ADDR'] : "";
    }
    return $ip; 
}

@Masterblank That could be simplified a lot and improved.

function getIp($ifNull = "") { # allow specification of null value
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
    }

    return $_SERVER['REMOTE_ADDR'] ? $_SERVER['REMOTE_ADDR'] : $ifNull;
}

getIp("127.0.0.1");
>> IP or 127.0.0.1 if it can't find it
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.