Skip to content

Instantly share code, notes, and snippets.

@irazasyed
Created March 5, 2022 01:02
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 irazasyed/87b1b2753eb35e552599406fdff226f3 to your computer and use it in GitHub Desktop.
Save irazasyed/87b1b2753eb35e552599406fdff226f3 to your computer and use it in GitHub Desktop.
PHP: Retrieve the IP address of the visitor.
<?php
/**
* Retrieve the IP address of the visitor.
*
* @return string
*/
function getIPAddress()
{
foreach (['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_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
return $ip;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment