The inaccurate IP obtained by php may be caused by the user using a proxy, so "$_SERVER['REMOTE_ADDR']" cannot sense the user's real IP. The solution is to define an "X-Forwarded-For" Entity header to get the real ip.
#The operating environment of this article: Windows7 system, PHP7.1, Dell G3 computer.
php The IP obtained is not real?
Everyone, something suddenly occurred to me. We are not using the usual $_SERVER[‘REMOTE_ADDR’]; to obtain the server’s intranet IP (most likely the server’s proxy IP). There is no problem with that code, and then we use a reverse proxy (nginx, etc.), and users may also use proxies, so a simple $_SERVER[‘REMOTE_ADDR’] cannot sense the user’s real IP.
But there is a parameter that can get the real user's address through the proxy IP. Extend the HTTP protocol. An entity header called X-Forwarded-For is defined.
Because we consider this, mainly for the advertising stars, after all, others can act as agents and boost sales.
[Recommended: PHP video tutorial]
The code is as follows:
//获取用户IP地址 public function getIp() { if(!empty($_SERVER["HTTP_CLIENT_IP"])) { $cip = $_SERVER["HTTP_CLIENT_IP"]; } else if(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) { $cip = $_SERVER["HTTP_X_FORWARDED_FOR"]; } else if(!empty($_SERVER["REMOTE_ADDR"])) { $cip = $_SERVER["REMOTE_ADDR"]; } else { $cip = ''; } preg_match("/[\d\.]{7,15}/", $cip, $cips); $cip = isset($cips[0]) ? $cips[0] : 'unknown'; unset($cips); return $cip; }
The above is the detailed content of What should I do if the IP obtained by php is inaccurate?. For more information, please follow other related articles on the PHP Chinese website!