Skip to content

Instantly share code, notes, and snippets.

@artifex404
Forked from cballou/get-ip-address-optimized.php
Last active December 20, 2015 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artifex404/6110795 to your computer and use it in GitHub Desktop.
Save artifex404/6110795 to your computer and use it in GitHub Desktop.
<?php
function get_ip_address() {
$ip_keys = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR');
foreach ($ip_keys as $key) {
if (array_key_exists($key, $_SERVER) === true) {
$items = explode(',', $_SERVER[$key]);
$value = (is_array($items)) ? end($items) : $items;
$ip = filter_var(trim($value), FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
}
}
return ($ip) ? $ip : '';
}
<?php
/**
* Retrieves the best guess of the client's actual IP address.
* Takes into account numerous HTTP proxy headers due to variations
* in how different ISPs handle IP addresses in headers between hops.
*/
function get_ip_address() {
$ip_keys = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR');
foreach ($ip_keys as $key) {
if (array_key_exists($key, $_SERVER) === true) {
$value = (is_array($items)) ? end($items) : $items;
$ip = filter_var(trim($value), FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
}
}
return ($ip) ? $ip : '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment