How to get clients real IP address in Laravel - PHP
In this article we will learn how to fetch real client's IP address in Laravel PHP . I have faced a problem on my project where i have to find client's real IP address. I have tried Laravel's built-in functions as well as PHP function but all of them were providing me server's IP address instead of client's.
So if you are also facing such issue then this solution should help you out. I have tried the following method's to fetch client's IP but does not work.
- $request->ip()
- \Request::ip()
- \request()->ip()
Along with these methods i have tried some RAW PHP codes also but does not work. Following is the solution where i got real client's IP which you can also give a try.
Solution :-
public function getClientIP(){ try{ if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) { $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"]; $_SERVER['HTTP_CLIENT_IP'] = $_SERVER["HTTP_CF_CONNECTING_IP"]; } $client = @$_SERVER['HTTP_CLIENT_IP']; $forward = @$_SERVER['HTTP_X_FORWARDED_FOR']; $remote = $_SERVER['REMOTE_ADDR']; if(filter_var($client, FILTER_VALIDATE_IP)){ $clientIp = $client; } elseif(filter_var($forward, FILTER_VALIDATE_IP)){ $clientIp = $forward; } else{ $clientIp = $remote; } return $clientIp; } catch(\Exception $e){ return false; } }
Thank you for reading this article 😊
For any query do not hesitate to comment 💬