1. Obtain the user’s real IP address
public static function getClientIp() { if (getenv('HTTP_CLIENT_IP')) { $ip = getenv('HTTP_CLIENT_IP'); } if (getenv('HTTP_X_REAL_IP')) { $ip = getenv('HTTP_X_REAL_IP'); } elseif (getenv('HTTP_X_FORWARDED_FOR')) { $ip = getenv('HTTP_X_FORWARDED_FOR'); $ips = explode(',', $ip); $ip = $ips[0]; } elseif (getenv('REMOTE_ADDR')) { $ip = getenv('REMOTE_ADDR'); } else { $ip = '0.0.0.0'; } return $ip; }
Note:
2. About REMOTE_ADDR
This variable obtains the IP address of the "direct source". The so-called "direct source" refers to the customer who directly requests the address end IP. In the case of a single server, this IP is very accurate and cannot be forged. Of course, not all programs must be single servers. For example, when load balancing is used (such as using haproxy or nginx for load balancing), this IP is the IP of the forwarding machine, because the process is client->Load Balancing-> ;Server. It is the server directly accessed by the load balancer instead of the client.3. Regarding HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP
It is impossible to obtain the client IP by directly using REMOTE_ADDR under load balancing. This is a problem that must be solved. Therefore, the load balancing side is derived, which adds the client IP to HEAD and sends it to the server, so that the server can obtain the client's real IP. Of course, what you call forgery is produced. After all, except for the fixed data in the HEAD protocol, other data are customizable. Recommended tutorial:The above is the detailed content of php cannot get real ip. For more information, please follow other related articles on the PHP Chinese website!