Middleware to detect the client ip and save it as a request attribute

v1.3.0 2019-03-29 09:10 UTC


Latest Version on Packagist Software License Build Status Quality Score Total Downloads SensioLabs Insight

Middleware to detect the client ip and save it as a request attribute.



This package is installable and autoloadable via Composer as middlewares/client-ip.

composer require middlewares/client-ip


$dispatcher = new Dispatcher([
	new Middlewares\ClientIp(),

    function ($request) {
        //Get the client ip
        $ip = $request->getAttribute('client-ip');

$response = $dispatcher->dispatch(new ServerRequest());


proxy(array $ips = [], array $headers = ['Forwarded', 'Forwarded-For', 'Client-Ip', 'X-Forwarded', 'X-Forwarded-For', 'X-Cluster-Client-Ip'])

Configure the detection through proxies. The first argument is an array of ips or cidr of the trusted proxies. If it's empty, no ip filtering is made. The second argument is a list of the headers to inspect. If it's not defined, uses the default value ['Forwarded', 'Forwarded-For', 'Client-Ip', 'X-Forwarded', 'X-Forwarded-For', 'X-Cluster-Client-Ip']. Disabled by default.

//Use proxies
$middleware = (new Middlewares\ClientIp())->proxy();

//Trust only some proxies by ip
$middleware = (new Middlewares\ClientIp())->proxy(['', '']);

//Trust only some proxies by ip using a specific header
$middleware = (new Middlewares\ClientIp())->proxy(['', ''], ['X-Forwarded-For']);

// Trust only some proxies by cidr range
// usefull when you have an autoscaled proxy(like haproxy) in a subnet
$middleware = (new Middlewares\ClientIp())->proxy(['', '']);

remote($remote = true)

Used to get the ip from localhost environment using http://ipecho.net/plain. Disabled by default.

attribute(string $attribute)

The attribute name used to store the ip in the server request. By default is client-ip.

Please see CHANGELOG for more information about recent changes and CONTRIBUTING for contributing details.

The MIT License (MIT). Please see LICENSE for more information.