Skip to content

Instantly share code, notes, and snippets.

@jrivero
Created March 15, 2012 10:02
Show Gist options
  • Save jrivero/2043408 to your computer and use it in GitHub Desktop.
Save jrivero/2043408 to your computer and use it in GitHub Desktop.
The most accurate way to retrieve a user's correct IP address in PHP
<?php
// found http://stackoverflow.com/questions/1634782/what-is-the-most-accurate-way-to-retrieve-a-users-correct-ip-address-in-php
function get_ip_address()
{
foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){
if (array_key_exists($key, $_SERVER) === true){
foreach (explode(',', $_SERVER[$key]) as $ip){
$ip = trim($ip); // just to be safe
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
return $ip;
}
}
}
}
}
?>
@hydrastro
Copy link

Accurate if you trust your user 🤣

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment