How to get client IP with PHP behind AWS Elastic Load Balancer

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>