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
+28.4k Golang : How to verify uploaded file is image or allowed file types
+14.9k Golang : convert string or integer to big.Int type
+21.1k Generate checksum for a file in Go
+20.7k Golang : How to run Golang application such as web server in the background or as daemon?
+3.8k JavaScript : Rounding number to decimal formats to display currency
+17.9k Golang : Get current URL example
+5.9k Swift : substringWithRange() function example
+14.9k Golang : Get file permission
+21.7k Golang : Gorilla mux routing example
+11.2k Golang : Search and extract certain XML data example
+8.2k Golang : does not implement flag.Value (missing Set method)
+8.4k Facebook : Getting the friends list with PHP return JSON format