系统有时会要求采集用户的IP地址,本文介绍了PHP程序获取用户真实IP地址的两种方法,希望对大家有所帮助。
获取用户IP地址方法一:
function GetRealIP() { static $realip; if (isset($_SERVER)){ if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){ $realip = $_SERVER["HTTP_X_FORWARDED_FOR"]; } else if (isset($_SERVER["HTTP_CLIENT_IP"])) { $realip = $_SERVER["HTTP_CLIENT_IP"]; } else { $realip = $_SERVER["REMOTE_ADDR"]; } } else { if (getenv("HTTP_X_FORWARDED_FOR")){ $realip = getenv("HTTP_X_FORWARDED_FOR"); } else if (getenv("HTTP_CLIENT_IP")) { $realip = getenv("HTTP_CLIENT_IP"); } else { $realip = getenv("REMOTE_ADDR"); } } if (strpos($realip, ',') === false) { $sUserIp = $realip; } else { $arrUserIp = explode(',' , $realip); $sUserIp = $arrUserIp[0]; } return $sUserIp; }
获取用户IP地址方法二:
function get_real_ip(){ if ( getenv( "HTTP_CLIENT_IP" ) && strcasecmp( getenv( "HTTP_CLIENT_IP" ), "unknown" ) ){ $ip = getenv( "HTTP_CLIENT_IP" ); }else if ( getenv( "HTTP_X_FORWARDED_FOR" ) && strcasecmp( getenv( "HTTP_X_FORWARDED_FOR" ), "unknown" ) ){ $ip = getenv( "HTTP_X_FORWARDED_FOR" ); }else if (getenv( "REMOTE_ADDR" ) && strcasecmp( getenv( "REMOTE_ADDR" ), "unknown" ) ){ $ip = getenv( "REMOTE_ADDR" ); }else if ( isset( $_SERVER[ 'REMOTE_ADDR' ] ) && $_SERVER[ 'REMOTE_ADDR' ]&& strcasecmp( $_SERVER[ 'REMOTE_ADDR' ], "unknown" ) ){ $ip = $_SERVER[ 'REMOTE_ADDR' ]; }else{ $ip = "unknown"; } if ( strpos( $ip, ',' ) ){ $ipArr = explode( ',', $ip ); $ip = $ipArr[ 0 ]; } return $ip; }
声明:如需转载,请注明来源于www.webym.net并保留原文链接:http://www.webym.net/jiaocheng/907.html