Get Real Client IP Behind Cloudflare in Laravel

Khalil Laleh
1 min readNov 20, 2020

--

Shah Goli — Tabriz

You can get the client real IP in PHP applications using following code:

$_SERVER['REMOTE_ADDR']

Laravel provides a convenient way to retrieve client IP:

/* Illuminate/Http/Request.php */
request()->ip()
or/* symfony/http-foundation.php */
request()->getClientIp()

But they are not working when your website is behind the Cloudflare or other proxies (e.g. a load balancer) and all return the Cloudflare Server IP.

However, there is a method in symfony/http-foundation/Request.php to bypass the proxy server IP. It is setTrustedProxies() method.

So, we can call this method in AppServiceProvider like this:

...use Symfony\Component\HttpFoundation\Request;...    public function boot()
{
/* This line set the Cloudflare's IP as a trusted proxy
Request::setTrustedProxies(
['REMOTE_ADDR'],
Request::HEADER_X_FORWARDED_FOR
);
}

After adding the above will result to return the real client IP from request()->ip & requset()->getClientIp() .

Consider you can pass the static IPs as first parameter to setTrustedProxies and works fine for proxy servers with fixed IP address. However, the Cloudflare changes the server and IP address and it is highly recommended to use ['REMOTE_ADDR'] as first parameter.

PS: This code has no issue on local and development environment.

--

--