只允许某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段
]