Note: This answer is outdated and dangerous. Request::ip()
will, since Laravel 5.5, return the correct IP address if configured to trust the load balancer's headers. The "custom method" presented here allows clients to set any IP address they like.
If you are under a load balancer, Laravel's \Request::ip()
always returns the balancer's IP:
echo $request->ip();
// server IP
echo \Request::ip();
// server IP
echo \request()->ip();
// server IP
echo $this->getIp(); //see the method below
// client IP
This custom method returns the real client IP:
public function getIp(){
foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){
if (array_key_exists($key, $_SERVER) === true){
foreach (explode(',', $_SERVER[$key]) as $ip){
$ip = trim($ip); // just to be safe
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
return $ip;
}
}
}
}
return request()->ip(); // it will return the server IP if the client IP is not found using this method.
}
In addition to this, I suggest you be very careful using Laravel's throttle middleware: It uses Laravel's Request::ip()
as well, so all your visitors will be identified as the same user and you will hit the throttle limit very quickly. I experienced this in a live environment and this caused big issues.
To fix this:
Illuminate\Http\Request.php
public function ip()
{
//return $this->getClientIp(); //original method
return $this->getIp(); // the above method
}
You can now also use Request::ip()
, which should return the real IP in production.