Getting user IP adress

Is this function enogh to get user ip?

function get_client_ip() {
    if (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    }
    elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    }
    elseif (isset($_SERVER['HTTP_FORWARDED'])) {
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    }
    elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    }
    else {
        $ipaddress = null;
    }
    
    if (filter_var($ipaddress, FILTER_VALIDATE_IP)) {
        return $ipaddress;
    } else {
        $ipaddress = null;
    }
}

Thanks!

If you want any script-kiddie to be able to fake an IP address they are using, this is enough.

If you want the only real IP address available (given your web-server is configured properly), it should be

function get_client_ip() {
    return $_SERVER['REMOTE_ADDR'];
}

everything else in this wall of text is an ordinary HTTP header, easily spoofed.

An enlightening reading

1 Like

Thank you very much!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.