If you have been a web developer for quite some time and are in the habit of sifting through your visitor and access logs, depending on your situation you may tend to notice that you do not always get the right client IP address from your users.
This can be caused by various issues like being behind a proxy or public reverse-proxy.
Why Would I Need the Right Client IP Address?
The most compelling reasons would fall under security purposes. Others are for validation, geo-filtering, spam prevention, and more. The easiest and most straightforward way to getting the visitors IP address in PHP would be to use the following:
// Get the visitors IP address
$ip_address = $_SERVER['REMOTE_ADDR'];
The problem is this call is not always reliable as it may provide the wrong address. For example, if the client is behind a proxy, then this call would most likely return the IP address of the proxy and not the client.
So what is a better solution? We can use PHP’s
getenv() function or
$_SERVER to iterate through the various variables. The difference here is that
getenv() returns the PHP environment variable while
$_SERVER returns the web server variables.
The following code is interchangeable between the two.
Here is a breakdown of what these variables contain:
1. $_SERVER[‘REMOTE_ADDR’] – This contains the IP address of the client. That is may not be the real address because of external factors like proxy servers etc unless you are using HTTPS.
2. $_SERVER[‘HTTP_CLIENT_IP’] – This will fetch the IP address where the user is accessing from shared Internet services.
3. $_SERVER[‘HTTP_X_FORWARDED_FOR’] – This will fetch the IP address from the users when they are behind a proxy. It can sometimes return internal or local IP address, which may not be useful in most circumstances. If forwarded from multiple IP addresses it can return a comma-separated list of addresses.
There you have it. That is the quick way to retrieve the correct client IP address to use in your code.