PHP Method instance code for getting client IP address
- 2021-11-10 09:06:18
- OfStack
Let's first understand the meaning of one variable:
$_SERVER ['REMOTE_ADDR']: The ip address of the user's computer browsing the current page
$_SERVER ['HTTP_CLIENT_IP']: ip for the client
$_SERVER ['HTTP_X_FORWARDED_FOR']: The gateway of the user's computer browsing the current page
$_SERVER ['HTTP_X_REAL_IP']: In nginx proxy mode, get the real IP of the client
/**
* Get client IP Address
*/
function real_ip()
{
$ip = $_SERVER['REMOTE_ADDR'];
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
foreach ($matches[0] AS $xip) {
if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
$ip = $xip;
break;
}
}
} elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (isset($_SERVER['HTTP_CF_CONNECTING_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CF_CONNECTING_IP'])) {
$ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
} elseif (isset($_SERVER['HTTP_X_REAL_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_X_REAL_IP'])) {
$ip = $_SERVER['HTTP_X_REAL_IP'];
}
return $ip;
}
Summarize
The above is the site to introduce you PHP access to the client IP address method example code, I hope to help you, if you have any questions welcome to leave me a message, this site will reply to you in time!