Recently we installed a WAF (web application firewall) which comes with a CDN setup. The CDN is basically a proxy that all traffic to our server goes through. Our site has many features based on the visitor’s IP – shopping cart for specific locations, different chat agents according to GEO location and even contact us information. Originally we were using
1 |
$_SERVER['REMOTE_ADDR'] |
to get the IP and send it to an external service which gave us the location. Behind a CDN the IP we got was the proxy’s IP. Luckily, there is a header especially for this situation which forwards the original IP to the end server. So we need to check several headers passed with fallback to others.
Here is the entire code I use:
1 2 3 4 5 6 7 8 9 10 11 12 |
function get_ip() { if (!empty($_SERVER['HTTP_X_REAL_IP'])) { $ip = $_SERVER['HTTP_X_REAL_IP']; } elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } return $ip; } |