Blog

Find out IP address with PHP

Find out IP address with PHP

From time to time you are faced with the challenge of trying to find out the IP address of the user.
For example, to quickly debug on the current IP or to grant or deny access to a specific IP address range.

Since you don’t always have direct access via SSH to customer servers and sometimes you can only do this with PHP, it’s a good idea to read the IP address and then continue working with it.

The following snippet reads various $_SERVER variables and then returns the first found IP.
If you want to prioritize a parameter, just move the key value in the $keys array a bit higher.

<?php

function getIp() {
    $keys = [
        'HTTP_CLIENT_IP', 
        'HTTP_X_FORWARDED_FOR',
        'HTTP_X_FORWARDED', 
        'HTTP_FORWARDED_FOR', 
        'HTTP_FORWARDED', 
        'REMOTE_ADDR'
    ];
    
    foreach($keys as $k) {
        if (isset($_SERVER[$k]) && !empty($_SERVER[$k]) && filter_var($_SERVER[$k], FILTER_VALIDATE_IP)) {
            return $_SERVER[$k];
        }
    }
    
    return null;
}

$ip = getIp();

?>

Leave a comment