PHP获取访客IP、判断IPv4 IPv6、判断当前域名http https

8623 阅读 暂无评论 47 字

帮客户做的一个案例,通过IP判断区域跳转和显示不同内容,以下是部分核心代码,做个记录。

获取访客IP

//获取IP
function GetIP(){ 
  static $ip = '';
  $ip = $_SERVER['REMOTE_ADDR'];
  if(isset($_SERVER['HTTP_CDN_SRC_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CDN_SRC_IP'])) {
    $ip = $_SERVER['HTTP_CDN_SRC_IP'];
  } elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
  } elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
    foreach ($matches[0] AS $xip) {
      if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
        $ip = $xip;
        break;
      }
    }
  }
  return $ip;
}

判断IPv4 IPv6

$ip = '192.168.1.1'
if (filter_var($ip, \FILTER_VALIDATE_IP,\FILTER_FLAG_IPV4)) {
  echo $ip;
}

$ip = '192.168.1.1'
if (filter_var($ip, \FILTER_VALIDATE_IP,\FILTER_FLAG_IPV6)) {
  echo $ip;
}

判断http https

function get_domain(){
    if ( ! empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off')
    {
        $protocol = "https://";
    }
    elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https')
    {
        $protocol = "https://";
    }
    elseif ( ! empty($_SERVER['HTTP_FROM_HTTPS']) && strtolower($_SERVER['HTTP_FROM_HTTPS']) !== 'off')
    {
        $protocol = "https://";
    }
    elseif ( ! empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off')
    {
        $protocol = "https://";
    }else if(!empty($_SERVER['HTTP_X_CLIENT_SCHEME']) && $_SERVER['HTTP_X_CLIENT_SCHEME']=='https'){
        $protocol = "https";
    }else{
        $protocol = "http";
    }
    if(isset($_SERVER['SERVER_PORT'])) {
        $port = ':' . $_SERVER['SERVER_PORT'];
        if((':80' == $port && 'http://' == $protocol) || (':443' == $port && 'https://' == $protocol)) {
            $port = '';
        }
    }else{
        $port = '';
    }
    if(isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
        $host = $_SERVER['HTTP_X_FORWARDED_HOST'].$port;
    }else if (isset($_SERVER['HTTP_HOST'])) {
        $host = $_SERVER['HTTP_HOST'].$port;
    }else if(isset($_SERVER['SERVER_NAME'])) {
        $host = $_SERVER['SERVER_NAME'].$port;
    }else if(isset($_SERVER['SERVER_ADDR'])) {
        $host = $_SERVER['SERVER_ADDR'].$port;
    }
    return $protocol;
}
文章评论 (0)
QQ咨询
QQ号码
979779692
微信咨询
微信二维码
在线咨询
微信咨询 QQ咨询
客服头像

截屏,微信识别二维码

微信号:itx2021

(点击微信号复制,添加好友)

微信号已复制,请打开微信添加好友!