Skip to main content
Robert Michalski

Get IP address of HTTP requests in PHP

This short guide will enable you to get the IP address from the headers of a request in PHP.

Use cases of knowing the IP of a visitor #

Knowing the IP address of a visitor opens up some interesting and useful use cases.

How to get the IP address of visitors #

The IP of the visitor is usually included in the headers of HTTP requests. Which header depends on the technology used by the software serving requests.

For Nginx and Apache, the most widely used web servers, the IP of the visitor is usually passed in the X-Forwarded-For header, sometimes in X-Real-IP on Nginx, it depends on the hosting setup.

When using a third-party proxy service, for instance Cloudflare, Incapsula, RackSpace etc. the IP of the visitor is included in custom headers of the respective service.

In PHP the IP of the client can be retrieved using the code $_SERVER[’REMOTE_ADDR’], however this contains the direct client, the last server/machine/software that called into PHP. It can be the IPs of your own servers, proxies or a third-party servers for instance Cloudflare IPs.

function get_ip_address_of_visitor() {
    $ip_keys = array(
        // Providers
        'HTTP_CF_CONNECTING_IP', // Cloudflare
        'HTTP_INCAP_CLIENT_IP', // Incapsula
        'HTTP_X_CLUSTER_CLIENT_IP', // RackSpace
        'HTTP_TRUE_CLIENT_IP', // Akamai

        // Proxies
        'HTTP_X_FORWARDED_FOR',
        'HTTP_X_FORWARDED',
        'HTTP_CLIENT_IP',
        'HTTP_X_REAL_IP',
        'HTTP_FORWARDED',
        'HTTP_FORWARDED_FOR',

        // Standard fallback
        'REMOTE_ADDR'
    );
    foreach ($ip_keys as $key) {
        $value = $_SERVER[$key];
        if (!empty($value) && is_string($value)) {
            foreach (explode(',', $value) as $ip) {
                // trim for safety measures
                $ip = trim($ip);
                // attempt to validate IP
                if (
                    //filter_var($ip, FILTER_VALIDATE_IP) // any valid IP address
                    filter_var($ip, FILTER_VALIDATE_IP,
                        FILTER_FLAG_NO_RES_RANGE | // filter reserved IP addresses
                        FILTER_FLAG_IPV4 // allow only IPv4 addresses
                    )
                ) {
                    return $ip;
                }
            }
        }
    }
    return $_SERVER['REMOTE_ADDR'];
}

$ip = get_ip_address_of_visitor();