During the interview a few days ago, I was asked what would be the problem with the IP address obtained through $_SERVER['SERVER_ADDR']
? It must be "if the user cannot obtain the real IP address through a proxy". Fortunately, the interviewer did not ask further questions. So how to get the user’s real IP address?
Analysis
Nowadays, many users do not dial-up directly to access the Internet, but access the Internet through routers or other proxies. If we want to obtain the real IP address of the user client, we cannot directly use
$_SERVER['SERVER_ADDR']
, because the IP address obtained in this way may be a **LAN** IP such as 192.168.1.99, not The user’s public IP address.Fortunately, when our access request passes through the public network routing or proxy server, the terminal will add the
X-Forwarded-For
header information to the HTTP request. We can use this request header to obtain the real identity of the client. IP address.
Code
<code><span><span><?php</span><span>/** * 获取用户的真实ip地址 *<span> @return</span> string */</span><span><span>function</span><span>get_client_ip</span><span>()</span>{</span><span>$headers</span> = <span>array</span>(<span>'HTTP_X_REAL_FORWARDED_FOR'</span>, <span>'HTTP_X_FORWARDED_FOR'</span>, <span>'HTTP_CLIENT_IP'</span>, <span>'REMOTE_ADDR'</span>); <span>foreach</span> (<span>$headers</span><span>as</span><span>$h</span>){ <span>$ip</span> = <span>$_SERVER</span>[<span>$h</span>]; <span>// 有些ip可能隐匿,即为unknown</span><span>if</span> ( <span>isset</span>(<span>$ip</span>) && strcasecmp(<span>$ip</span>, <span>'unknown'</span>) ){ <span>break</span>; } } <span>if</span>( <span>$ip</span> ){ <span>// 可能通过多个代理,其中第一个为真实ip地址</span><span>list</span>(<span>$ip</span>) = explode(<span>', '</span>, <span>$ip</span>, <span>2</span>); } <span>/* 如果是服务器自身访问,获取服务器的ip地址(该地址可能是局域网ip) if ('127.0.0.1' == $ip){ $ip = $_SERVER['SERVER_ADDR']; } */</span><span>return</span><span>$ip</span>; } <span>?></span></span></code>
Copyright Statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.
The above introduces PHP to obtain the user's real IP, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.