cxfoot/components/IPUtils.php
2023-10-27 14:25:12 +08:00

100 lines
3.0 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* @author Any
* @description KISS
* @date 2020-12-24
* @version 1.0.0
*
* _____LOG_____
*
*/
namespace app\components;
class IPUtils
{
public static function getIp()
{
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 = "";
}
$is = self::isIp($ip);
if(!$is){
$ip = \Yii::$app->request->userIP;
}
$is_lan_ip = self::isLanIp($ip);
if(!$is_lan_ip){
return $ip;
}
return $ip;
}
/**
* ip地址判断
* @param String $gonten 需要判断的字符串
* @return ture or false
*/
public static function isIp($gonten){
$ip=explode(".",$gonten);
for($i=0;$i<count($ip);$i++)
{
if($ip[$i]>255){
return false;
}
}
return preg_match("/^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$/",$gonten);
}
/**
* 判断ip地址是否是内网ip
* @param String $gonten 需要判断的字符串
* @return ture or false true则为内网IP否则不是
*/
public static function isLanIp($gonten){
if($gonten == "127.0.0.1"){
return true;
}
$ip=explode(".",$gonten);
//A类 10.0.0.0--10.255.255.255
if($ip[0] == 10){
for($i=1;$i<count($ip);$i++)
{
if($ip[$i]>255){
return false;
}
}
return preg_match("/^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$/",$gonten);
}
//B类 172.16.0.0--172.31.255.255
if($ip[0] == 171 && $ip[1] >= 16 && $ip <= 31){
for($i=2;$i<count($ip);$i++)
{
if($ip[$i]>255){
return false;
}
}
return preg_match("/^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$/",$gonten);
}
//C类 192.168.0.0--192.168.255.255
if($ip[0] == 192 && $ip[1] == 168){
for($i=2;$i<count($ip);$i++)
{
if($ip[$i]>255){
return false;
}
}
return preg_match("/^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$/",$gonten);
}
return false;
}
}