FastAdmin中如何只允许某IP段访问和只允指定IP访问

只允许某IP段访问

php 复制代码
/**
 * IP段访问限制
 *
 * @param string $ipSegment 允许的IP段,例如:10.144.39.*
 * @return bool
 */
protected function checkIpSegment($ipSegment)
{
    $ip = $this->request->ip();

    // 将 * 转换为正则匹配
    $pattern = '/^' . str_replace(
        ['.', '*'],
        ['\.', '\d{1,3}'],
        $ipSegment
    ) . '$/';

    return preg_match($pattern, $ip) === 1;
}

// 调用
if (!$this->checkIpSegment('10.144.39.*')) {
    return json([
        'status' => 2,
        'msg'    => '该IP段无权限访问',
        'data'   => $this->request->ip()
    ]);
}

只允许指定 IP 访问

php 复制代码
/**
 * 指定IP访问限制
 *
 * @param array $allowedIps 允许访问的IP列表
 * @return bool
 */
protected function checkAllowedIp(array $allowedIps)
{
    $ip = $this->request->ip();

    return in_array($ip, $allowedIps, true);
}

// 调用
$allowedIps = [
    '10.144.39.132',
    '10.144.39.133',
    '10.144.39.134',
];

if (!$this->checkAllowedIp($allowedIps)) {
    return json([
        'status' => 2,
        'msg'    => '该IP无权限访问',
        'data'   => $this->request->ip()
    ]);
}

统一成一个方法

php 复制代码
/**
 * IP访问权限检查
 *
 * 支持:
 * 10.144.39.132   指定IP
 * 10.144.39.*     IP段
 * 10.144.*.*      IP段
 *
 * @param array $allowedIps
 * @return bool
 */
protected function checkIp(array $allowedIps)
{
    $ip = $this->request->ip();

    foreach ($allowedIps as $allowedIp) {

        // 指定IP
        if ($ip === $allowedIp) {
            return true;
        }

        // IP段
        if (strpos($allowedIp, '*') !== false) {
            $pattern = '/^' . str_replace(
                ['.', '*'],
                ['\.', '\d{1,3}'],
                $allowedIp
            ) . '$/';

            if (preg_match($pattern, $ip)) {
                return true;
            }
        }
    }

    return false;
}

// 调用
if (!$this->checkIp([
    '10.144.39.132',
    '10.144.39.133',
    '10.144.40.*',
])) {
    return json([
        'status' => 2,
        'msg'    => '该IP无权限访问',
        'data'   => $this->request->ip()
    ]);
}

后期只需要维护:

php 复制代码
[
    '10.144.39.132', // 指定IP
    '10.144.39.133', // 指定IP
    '10.144.40.*',   // IP段
]
相关推荐
张小勇24 天前
fastadmin try中不能使用success和error方法解决方案
fastadmin
withoutfear1 个月前
Fastadmin中fieldlist 二维数组某个字段需要上传单图和多图
前端·html·fastadmin
JSON_L1 个月前
Fastadmin后台使用validate进行表单验证
php·fastadmin
JSON_L1 个月前
Fastadmin关联查询报错 method not exist:think\db\Query->XXX
php·fastadmin
appleคิดถึง3 个月前
fastadmin后台订单管理页面显示出订单分类
fastadmin
宋拾壹3 个月前
fastadmin列表中查看列表,并且添加增加相应的数据
javascript·php·fastadmin
cq林志炫3 个月前
fastadmin 如何限制访问public\assets\libs目录下面的所有html文件
html·php·fastadmin
withoutfear3 个月前
Fastadmin中获取IP和手机号归属地信息
php·thinkphp·fastadmin·ip归属地·手机号归属地
宋拾壹4 个月前
fastadmin upload上传图片压缩
图片压缩·fastadmin