PHP gets the real IP of the client

  • 2020-03-31 17:07:46
  • OfStack

 
function GetIP(){ 
if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) 
$ip = getenv("HTTP_CLIENT_IP"); 
else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) 
$ip = getenv("HTTP_X_FORWARDED_FOR"); 
else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) 
$ip = getenv("REMOTE_ADDR"); 
else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) 
$ip = $_SERVER['REMOTE_ADDR']; 
else 
$ip = "unknown"; 
return($ip); 
} 

Regist = off
If ($register_globals! = 1) {
@ extract ($_SERVER, EXTR_SKIP);
@ extract ($_COOKIE EXTR_SKIP);
@ extract ($_SESSION EXTR_SKIP);
@ extract ($_POST, EXTR_SKIP);
@ extract ($_FILES, EXTR_SKIP);
@ extract ($_GET, EXTR_SKIP);
@ extract ($_ENV EXTR_SKIP);
}
REMOTE_ADDR is easy to understand. The PHP manual explains that it is a predetermined variable. And HTTP_x_FORWARDED_FOR, looking up some stuff on the web, that's what it says
In PHP, you use $_SERVER["REMOTE_ADDR"] to get the client's IP address, but if the client is using a proxy server to access it, you get the proxy server's IP address, not the real client's IP address. To get the real IP address of the client through the proxy server, use $_SERVER["HTTP_X_FORWARDED_FOR"] to read it.
It is important to note, however, that not every proxy server can use $_SERVER["HTTP_X_FORWARDED_FOR"] to read the real IP of the client, and some still read the proxy server's IP using this method.

As for HTTP_CLIENT_IP, a post says
'HTTP_CLIENT_IP' is the user's IP, and 'HTTP_X_FORWARDED_FOR' is the proxy's IP
These IP header messages may not be available (because different browsers and different network devices may send different IP header messages). So PHP tries to determine each IP header message, and if there is one, it takes one.

Related articles: