Last active
June 15, 2023 10:51
-
-
Save iomoath/38d8477ef06f7f61d5c95ebb8a68c2c2 to your computer and use it in GitHub Desktop.
Get client actual IP address - Based on HTTP headers - Detect Transparent proxy
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
<?php | |
function get_client_ip() | |
{ | |
try { | |
// Get real visitor IP behind CloudFlare network | |
if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) { | |
$_SERVER["REMOTE_ADDR"] = $_SERVER["HTTP_CF_CONNECTING_IP"]; | |
$_SERVER["HTTP_CLIENT_IP"] = $_SERVER["HTTP_CF_CONNECTING_IP"]; | |
} | |
$ip_candidates = [ | |
$_SERVER["HTTP_CLIENT_IP"] ?? null, | |
$_SERVER["HTTP_X_FORWARDED_FOR"] ?? null, | |
$_SERVER["HTTP_FORWARDED_FOR"] ?? null, | |
$_SERVER["HTTP_X_FORWARDED"] ?? null, | |
$_SERVER["HTTP_FORWARDED"] ?? null, | |
$_SERVER["HTTP_FORWARDED_FOR_IP"] ?? null, | |
$_SERVER["X_FORWARDED_FOR"] ?? null, | |
$_SERVER["FORWARDED_FOR"] ?? null, | |
$_SERVER["CLIENT-IP"] ?? null, | |
$_SERVER["FORWARDED_FOR_IP"] ?? null, | |
$_SERVER["HTTP_X_APPENGINE_USER_IP"] ?? null, | |
$_SERVER["HTTP_PROXY_CONNECTION"] ?? null, | |
$_SERVER["HTTP_VIA"] ?? null, | |
$_SERVER["VIA"] ?? null, | |
$_SERVER["CF-Connecting-IP"] ?? null, | |
$_SERVER["HTTP_X_REAL_IP"] ?? null, | |
$_SERVER["CLIENT_IP"] ?? null, | |
$_SERVER["HTTP_XROXY_CONNECTION"] ?? null, | |
$_SERVER["HTTP_X_CLUSTER_CLIENT_IP"] ?? null, | |
$_SERVER["CLIENT-IP"] ?? null, | |
$_SERVER["HTTP_COMING_FROM"] ?? null, | |
$_SERVER["HTTP_X_COMING_FROM"] ?? null, | |
$_SERVER["MT-PROXY-ID"] ?? null, | |
$_SERVER["X-PROXY-ID"] ?? null, | |
$_SERVER["REMOTE_ADDR"] ?? null, | |
]; | |
foreach ($ip_candidates as $candidate) { | |
if (is_null($candidate)) { | |
continue; | |
} | |
$parts = explode(",", $candidate); | |
if (empty($parts)) { | |
continue; | |
} | |
$ip = preg_replace("/\s+/", "", $parts[0]); | |
if (filter_var($ip, FILTER_VALIDATE_IP)) { | |
return $ip; | |
} | |
} | |
} catch (Exception $ex) { | |
return "Error"; | |
} | |
return "UNKNOWN"; | |
} | |
echo get_client_ip(); | |
exit(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment