In the light of the latest httpoxy vulnerabilities, there is another variable, that is widely misused.
HTTP_X_FORWARDED_FOR is often used to detect the client IP address, but without any additional checks, this can lead to security issues, especially when this IP is later used for authentication or in SQL queries without sanitization.
Most of the code samples available ignore the fact that HTTP_X_FORWARDED_FOR can actually be considered as information provided by the client itself and therefore is not a reliable source to detect clients IP address. Some of the samples do add a warning about the possible misuse, but still lack any additional check in the code itself.
So here is an example of function written in PHP, how to detect a client IP address, if you know that client may be behind a proxy and you know this proxy can be trusted. If you don't known any trusted proxies, you can just use REMOTE_ADDR
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0