现在的位置: 网页制作教程网站制作教程 >正文
php网上学习

PHP如何获取用户的IP地址

发表于2017/4/22 网站制作教程 0条评论 ⁄ 热度 964℃

系统有时会要求采集用户的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;
}
  • 暂无评论