I am trying to get the client\'s IP address in Laravel.
It is easy to get a client\'s IP in PHP by using $_SERVER[\"REMOTE_ADDR\"]
. It is working fine
For Laravel 5 you can use the Request object. Just call its ip()
method, something like:
$request->ip();
$ip = $_SERVER['REMOTE_ADDR'];
If you want client IP and your server is behind aws elb, then user the following code. Tested for laravel 5.3
$elbSubnet = '172.31.0.0/16';
Request::setTrustedProxies([$elbSubnet]);
$clientIp = $request->ip();
Use request()->ip()
.
From what I understand, since Laravel 5 it's advised/good practice to use the global functions like:
response()->json($v);
view('path.to.blade');
redirect();
route();
cookie();
And, if anything, when using the functions instead of the static notation my IDE doesn't light up like a Christmas tree.
If you have multiple layer proxies just like CDN + Load Balancer.
Using Laravel Request::ip() function will get right-most proxy IP but not client IP.
You may try following solution.
app/Http/Middleware/TrustProxies.php
protected $proxies = ['0.0.0.0/0'];
Reference: https://github.com/fideloper/TrustedProxy/issues/107#issuecomment-373065215
There are two things to take care of:
Get a helper function that returns a Illuminate\Http\Request
and call the ->ip()
method:
request()->ip();
Think of your server configuration, it may use a proxy or load-balancer
, especially in an AWS ELB configuration.
If this is your case you need to follow "Configuring Trusted Proxies" or maybe even set a "Trusting All Proxies" option.
Why? Because being your server will be getting your proxy/load-balancer
IP instead.
If you are on the AWS balance-loader, go to App\Http\Middleware\TrustProxies
and make $proxies
declaration look like this:
protected $proxies = '*';
Now test it and celebrate because you just saved yourself from having trouble with throttle middleware. It also relies on request()->ip()
and without setting "TrustProxies" up, you could have all your users blocked from logging in instead of blocking only the culprit's IP.
And because throttle middleware is not explained properly in the documentation, I recommend watching "laravel 5.2 tutorial for beginner, API Rate Limiting"
Tested in Laravel 5.7