If a PHP application server is located behind Amazon Web Service’s Elastic Load Balancer, or another type of proxy server, it is likely that the traditional mechanism for retrieving the end user’s IP address will not work as expected. As the request passes through the server, the REMOTE_ADDR
key of the $_SERVER
variable changes to that of the load balancer; however, all is not lost. In particular, using the AWS Elastic Load Balancer results in the client IP being transferred to another key in the $_SERVER
variable—HTTP_X_FORWARDED_FOR
.
The code to find the correct IP address is quite simple:
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR']) { $clientIpAddress = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $clientIpAddress = $_SERVER['REMOTE_ADDR']; }
Keep in mind, we have made no considerations for IP spoofing. As always, ensure you protect yourself with a variety of security techniques.