When working in one of my project, I wanted to get client devices' IP Address. So I search on how to accurately get client IP address.
If your project is in Laravel framework, Laravel's \Request::ip()
or $request->ip()
always returns the load balancer's IP. The easiest way to get the client’s IP address is using PHP's global $_SERVER['REMOTE_ADDR']
or $_SERVER['REMOTE_HOST']
variables but sometimes this does not return the correct IP address of the client, so we have to use some other server variables to get the IP address.
The below functions I found most accurate way to get client/users IP address.
getenv()
function is used to get the value of an environment variable in PHP.
function getClientIP() {
$ip_address = '';
if (getenv('HTTP_CLIENT_IP')) {
$ip_address = getenv('HTTP_CLIENT_IP');
} elseif(getenv('HTTP_X_FORWARDED_FOR')) {
$ip_address = getenv('HTTP_X_FORWARDED_FOR');
} elseif(getenv('HTTP_X_FORWARDED')) {
$ip_address = getenv('HTTP_X_FORWARDED');
} elseif(getenv('HTTP_FORWARDED_FOR')) {
$ip_address = getenv('HTTP_FORWARDED_FOR');
} elseif(getenv('HTTP_FORWARDED')) {
$ip_address = getenv('HTTP_FORWARDED');
} elseif(getenv('REMOTE_ADDR')) {
$ip_address = getenv('REMOTE_ADDR');
} else {
$ip_address = 'UNKNOWN';
}
return $ip_address;
}
Or using $_SERVER
array that contains server variables created by the web server.
function getClientIP() {
$ip_address = '';
if (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ip_address = $_SERVER['HTTP_CLIENT_IP'];
} elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
$ip_address = $_SERVER['HTTP_X_FORWARDED'];
} elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
$ip_address = $_SERVER['HTTP_FORWARDED_FOR'];
} elseif (isset($_SERVER['HTTP_FORWARDED'])) {
$ip_address = $_SERVER['HTTP_FORWARDED'];
} elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip_address = $_SERVER['REMOTE_ADDR'];
} else {
$ip_address = 'UNKNOWN';
}
return $ip_address;
}
I hope you like this article and it will help in your work.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
How To Make Money Blogging
With the revolution in smartphone market...Django - How to Uploading File with Example
It is generally useful for a web app to...Laravel 8 - jQuery Ajax File Upload with Progress Bar Tutorial
In this article, i will share with you h...Autocomplete Search with Image and Custom HTML in jQuery
Today I will show you on your website to...How To Create Custom Helper In Laravel 5.5
Today in this article we are share with...