How to get the client IP address in PHP

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

1. Contains the real IP address of the client. $_SERVER['REMOTE_ADDR'] 

2. Fetch the host name from which the user is viewing the current page.  $_SERVER['REMOTE_HOST'] 

3. Fetch the IP address when the user is from shared Internet services. $_SERVER['HTTP_CLIENT_IP'] 

4. Fetch the IP address from the user when he/she is behind the proxy. $_SERVER['HTTP_X_FORWARDED_FOR'] 

Function get the real IP address


function get_the_real_IP() {
    $ip = '';
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ip = htmlspecialchars($_SERVER['HTTP_CLIENT_IP']);
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ip = htmlspecialchars($_SERVER['HTTP_X_FORWARDED_FOR']);
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ip = htmlspecialchars($_SERVER['HTTP_X_FORWARDED']);
    else if(isset($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
        $ip  = htmlspecialchars($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']);
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ip = htmlspecialchars($_SERVER['HTTP_FORWARDED_FOR']);
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ip  = htmlspecialchars($_SERVER['HTTP_FORWARDED']);
    else if(isset($_SERVER['REMOTE_ADDR']))
        $ip = htmlspecialchars($_SERVER['REMOTE_ADDR']);
    else
        $ip = 'uncnown';
    return $ip ;
}

Leave a Reply