Last active
March 19, 2023 22:19
-
-
Save danielhaim1/5e84cbbaf9eaacb207b3db1674de39ed to your computer and use it in GitHub Desktop.
The get_client_ip() function has been updated to use a whitelist approach to validate the IP address. It checks if the IP address is in one of the trusted ranges specified in an array, and returns the IP address if it is. The function also includes a get_ip_address() function that returns the IP address by checking several server variables. A se…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function get_client_ip() { | |
$ipaddress = 'UNKNOWN'; | |
$trusted_ranges = [ | |
'192.0.2.0/24', // Example trusted range | |
// Add more trusted ranges here | |
]; | |
foreach ($trusted_ranges as $range) { | |
if (ip_in_range(get_ip_address(), $range)) { | |
$ipaddress = get_ip_address(); | |
break; | |
} | |
} | |
return $ipaddress; | |
} | |
function get_ip_address() { | |
if (isset($_SERVER['HTTP_CLIENT_IP'])) { | |
return $_SERVER['HTTP_CLIENT_IP']; | |
} elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { | |
return $_SERVER['HTTP_X_FORWARDED_FOR']; | |
} elseif(isset($_SERVER['HTTP_X_FORWARDED'])) { | |
return $_SERVER['HTTP_X_FORWARDED']; | |
} elseif(isset($_SERVER['HTTP_FORWARDED_FOR'])) { | |
return $_SERVER['HTTP_FORWARDED_FOR']; | |
} elseif(isset($_SERVER['HTTP_FORWARDED'])) { | |
return $_SERVER['HTTP_FORWARDED']; | |
} elseif(isset($_SERVER['REMOTE_ADDR'])) { | |
return $_SERVER['REMOTE_ADDR']; | |
} else { | |
return 'UNKNOWN'; | |
} | |
} | |
function ip_in_range($ip, $range) { | |
list($subnet, $bits) = explode('/', $range); | |
$subnet = ip2long($subnet); | |
$mask = -1 << (32 - $bits); | |
$subnet &= $mask; // Clear bits in subnet outside the mask | |
$ip = ip2long($ip); | |
$ip &= $mask; // Clear bits in IP outside the mask | |
return ($subnet == $ip); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment