Home > Article > Backend Development > How to get the real IP of the client with PHP_PHP tutorial
REMOTE_ADDR can only obtain the IP set in the visitor's local connection, such as the 10. , if the visitor uses a proxy server, the IP of the proxy server will not be obtained, but the real IP of the visitor's gateway will be obtained. If this function is applied to a web page with restricted IP access, others will not be able to access the page even through the proxy server in the restricted IP access segment.
A function is provided below:
<?php // 定义一个函数getIP() function getIP() { global $ip; if (getenv("HTTP_CLIENT_IP")) $ip = getenv("HTTP_CLIENT_IP"); else if(getenv("HTTP_X_FORWARDED_FOR")) $ip = getenv("HTTP_X_FORWARDED_FOR"); else if(getenv("REMOTE_ADDR")) $ip = getenv("REMOTE_ADDR"); else $ip = "Unknow"; return $ip; } // 使用方法: echo getIP(); ?>
getenv("REMOTE_ADDR") is used to obtain the client's IP address, but if the client uses a proxy server to access, what is obtained is the IP address of the proxy server, not the real client IP address. To obtain the client's real IP address through the proxy server, use getenv("HTTP_X_FORWARDED_FOR") to read it.
But if the client does not access through a proxy server, the value obtained with getenv("HTTP_X_FORWARDED_FOR") will be empty.
else if(getenv("HTTP_X_FORWARDED_FOR")) $ip = getenv("HTTP_X_FORWARDED_FOR");
means that if the value obtained by getenv("HTTP_X_FORWARDED_FOR") is not empty (that is, when the client uses a proxy server), the variable $ip is equal to the real IP value obtained by getenv("HTTP_X_FORWARDED_FOR").
If the value obtained by the above else if(getenv("HTTP_X_FORWARDED_FOR")) is empty (that is, no proxy server is used), the following $ip = getenv("HTTP_X_FORWARDED_FOR"); line statement will not be executed.
In this case it has been confirmed that the client does not use a proxy server, thus passing
else if(getenv("REMOTE_ADDR")) $ip = getenv("REMOTE_ADDR");
These two lines of statements obtain the client’s IP address, which is also the real IP address.