Home  >  Article  >  Backend Development  >  php cannot get real ip

php cannot get real ip

王林
王林Original
2019-09-29 17:46:244068browse

php cannot get real ip

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:

##$ The difference between _SERVER and getenv is that getenv does not support PHP running in IIS isapi mode. The getenv("REMOTE_ADDR") function can obtain the IP address normally under apache, but has no effect in iis. The $_SERVER['REMOTE_ADDR'] function can successfully obtain the visitor's ip address in apache, but also under iis. efficient.

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:

PHP video 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn