Skip to content

Instantly share code, notes, and snippets.

@eyupfidan
Created September 19, 2024 07:20
Show Gist options
  • Save eyupfidan/fc0c04e07e4ee893d153a7b28c641721 to your computer and use it in GitHub Desktop.
Save eyupfidan/fc0c04e07e4ee893d153a7b28c641721 to your computer and use it in GitHub Desktop.
This function retrieves the user's IP address by checking various server variables. It filters out private and reserved IP ranges to ensure only public IPs are returned. If no valid IP is found, it returns 'local'.
<?php
/**
* Get the user's IP address from various possible sources.
* It filters out private and reserved IP ranges.
* If no valid public IP is found, returns 'local'.
*
* @return string User's IP address or 'local' if not found.
*/
function getUserIpAddress() {
// Define the list of possible IP address sources
$ipSources = [
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR'
];
// Iterate through the sources and return the first valid IP address
foreach ($ipSources as $source) {
if (!empty($_SERVER[$source])) {
// If the source is HTTP_X_FORWARDED_FOR, it may contain multiple IP addresses
if ($source === 'HTTP_X_FORWARDED_FOR') {
$ipList = explode(',', $_SERVER[$source]);
foreach ($ipList as $ip) {
$ip = trim($ip); // Clean up the IP address
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
return $ip; // Return the first valid public IP address
}
}
} else {
$ip = $_SERVER[$source];
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
return $ip; // Return the first valid public IP address
}
}
}
}
// Return 'local' if no valid IP is found
return 'local';
}
// Retrieve and display the user's IP address
$userIp = getUserIpAddress();
echo 'User IP Address: ' . $userIp;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment