猿问

如何从访客获得真实IP?

我正在使用以下PHP代码获取访问者的IP地址:


<?php echo $_SERVER['REMOTE_ADDR']; ?>

但是,当访客使用Proxy时,我无法从访客那里获得真实的IP地址。在这种情况下,是否可以获取访客的IP地址?


倚天杖
浏览 605回答 3
3回答

繁星coding

这是我见过的最常见的技术:function getUserIP() {&nbsp; &nbsp; if( array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) {&nbsp; &nbsp; &nbsp; &nbsp; if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',')>0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $addr = explode(",",$_SERVER['HTTP_X_FORWARDED_FOR']);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return trim($addr[0]);&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return $_SERVER['HTTP_X_FORWARDED_FOR'];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; return $_SERVER['REMOTE_ADDR'];&nbsp; &nbsp; }}请注意,这并不保证您将始终获得正确的用户IP,因为有很多隐藏它的方法。

浮云间

这是我的方法:&nbsp;function getRealUserIp(){&nbsp; &nbsp; switch(true){&nbsp; &nbsp; &nbsp; case (!empty($_SERVER['HTTP_X_REAL_IP'])) : return $_SERVER['HTTP_X_REAL_IP'];&nbsp; &nbsp; &nbsp; case (!empty($_SERVER['HTTP_CLIENT_IP'])) : return $_SERVER['HTTP_CLIENT_IP'];&nbsp; &nbsp; &nbsp; case (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) : return $_SERVER['HTTP_X_FORWARDED_FOR'];&nbsp; &nbsp; &nbsp; default : return $_SERVER['REMOTE_ADDR'];&nbsp; &nbsp; }&nbsp;}如何使用:$ip = getRealUserIp();
随时随地看视频慕课网APP
我要回答