How to get the client IP address in PHP

When working in one of my project, I wanted to get client devices' IP Address. So I search on how to accurately get client IP address.

If your project is in Laravel framework, Laravel's \Request::ip() or $request->ip() always returns the load balancer's IP. The easiest way to get the client’s IP address is using PHP's global $_SERVER['REMOTE_ADDR'] or $_SERVER['REMOTE_HOST'] variables but sometimes this does not return the correct IP address of the client, so we have to use some other server variables to get the IP address.

The below functions I found most accurate way to get client/users IP address.

getenv() function is used to get the value of an environment variable in PHP.

function getClientIP() {
    
    $ip_address = '';

    if (getenv('HTTP_CLIENT_IP')) {
        $ip_address = getenv('HTTP_CLIENT_IP');
    } elseif(getenv('HTTP_X_FORWARDED_FOR')) {
        $ip_address = getenv('HTTP_X_FORWARDED_FOR');
    } elseif(getenv('HTTP_X_FORWARDED')) {
        $ip_address = getenv('HTTP_X_FORWARDED');
    } elseif(getenv('HTTP_FORWARDED_FOR')) {
        $ip_address = getenv('HTTP_FORWARDED_FOR');
    } elseif(getenv('HTTP_FORWARDED')) {
       $ip_address = getenv('HTTP_FORWARDED');
    } elseif(getenv('REMOTE_ADDR')) {
        $ip_address = getenv('REMOTE_ADDR');
    } else {
        $ip_address = 'UNKNOWN';
    }
    
    return $ip_address;
}

Or using $_SERVER array that contains server variables created by the web server.

function getClientIP() {
    
    $ip_address = '';
    
    if (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip_address = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
        $ip_address = $_SERVER['HTTP_X_FORWARDED'];
    } elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
        $ip_address = $_SERVER['HTTP_FORWARDED_FOR'];
    } elseif (isset($_SERVER['HTTP_FORWARDED'])) {
        $ip_address = $_SERVER['HTTP_FORWARDED'];
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip_address = $_SERVER['REMOTE_ADDR'];
    } else {
        $ip_address = 'UNKNOWN';
    }
    
    return $ip_address;
}

I hope you like this article and it will help in your work. Please follow us on Twitter and like us on Facebook.

Tags:

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

No Comment