How to get client IP address in Laravel/PHP
We can get the IP address of the client in Laravel using the simple built-in function like:
Request::ip(), request()->ip. But this will be giving us the server/machine's IP address where the application is deployed instead of the actual client IP address if we are behind the load balancer. In this case, we need to write our custom function that will get the client's IP address for us.
For this, we have written our own custom function that gets the job done for us. Just call the getClientIPAddress(), it doesn't matter either you are behind the proxy, load balancer, or not.
public function getClientIPAddress(){
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_address){
$ip_address = trim($ip_address);
if(filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
return $ip_address;
}
}
}
}
// if the IP address not found, or something doesn't work as expected, then we will be returning the IP address ( in most cases it can be the server IP address.
return request()->ip();
}
Hope this will work in all the cases.