In PHP, the common way to obtain the requested IP is generally through three super global variables, but it is obvious that the three methods of obtaining the IP are not completely reliable.
$_SERVER['REMOTE_ADDR']; // 客户端与服务器握手IP,如果使用代理则会获取到代理IP $_SERVER['HTTP_CLIENT_IP']; // 代理服务器发送的HTTP头(可伪造) $_SERVER['HTTP_X_FORWARDED_FOR']; // 用户是在哪个IP使用的代理(可伪造)
If the domain name has not been proxied, the generally safe way is REMOTE_ADDR. If it is an overseas network, the safest way is for cloud vendors to provide reliable source IP acquisition methods, such as those provided by Google Cloud:
When no forged IP appears, X-forwarded-For is usually the real IP of the client, load balancing IP
When a forged IP appears, Google Cloud will forge the content For prefixing, the format is
So regardless of whether it is forged or not, we can cut the string by commas and find the penultimate X-forwarded- For the value, you can get the real client IP.
Of course, if the domain name cloud vendor does not provide similar domain name information, we cannot simply obtain it through super global variables.
When the domain name cloud vendor does not provide the corresponding request source IP information, we can also negotiate a confirmation mechanism through server interaction.
Similar: Add source IP information to the HTTP request header for judgment. Since it is a communication process between servers, the forger cannot know the specific information content of the forgery, so usually such interaction is reliable.
Judgment logic process
Server A: Add the variable MY_REALIP_c32fsjk234 => "1.2.3.4" to the HTTP request header. At this time, please note that the variable name should not be too large. Simple, and it is best for both parties to agree on a random key as the variable name, similar to MY_REALIP_c32fsjk234
Accepting requester B: Use $_SERVER['MY_REALIP_c32fsjk234'] to determine whether the request header contains the MY_REALIP_c32fsjk234 variable. If so, obtain the corresponding IP as real IP.
Original link: https://blog.csdn.net/panguangyuu/article/details/122211682
Recommended reading:
The above is the detailed content of How to get the real IP with PHP. For more information, please follow other related articles on the PHP Chinese website!