PHP : Get client IP address
Knowing who is accessing your web server can be useful for tracking a user's activity. In this tutorial, we will learn how to get client IP address with PHP.
In a straight forward manner, this should be get your the IP address of a client
$_SERVER['REMOTE_ADDR']
However, sometimes the user access your web server via a proxy or load balancer ( such as in cloud hosting, behind a LAN, etc ) and the above code will give you the IP address of the proxy or load balancer.
You need to get the HTTP Request header information "X-Forwarded-For (XFF)" in order to get the real IP address of the client. To do that you can use
$_SERVER['HTTP_X_FORWARDED_FOR']
and
$_SERVER['HTTP_CLIENT_IP']
The PHP code snippet below should do the job :
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$client_ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$client_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$client_ip = $_SERVER['REMOTE_ADDR'];
}
Hope this simple tutorial can be useful to you.
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.4k Golang : On lambda, anonymous, inline functions and function literals
+10.6k CodeIgniter : Import Linkedin data
+22.9k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
+46.2k Golang : How to convert JSON string to map and slice
+6.2k Golang : Use modern ciphers only in secure connection
+4.5k Golang : Intercept, inject and replay HTTP traffics from web server
+39.2k Golang : How to count duplicate items in slice/array?
+3.8k Golang : How to pass data between controllers with JSON Web Token
+14.9k Golang : Get IP addresses of a domain name
+6.6k Golang : Gorrila set route name and get the current route name
+4.8k Golang : Error handling methods
+15.8k Golang : Get number of CPU cores