thinkphp6: 使用middleware限制ip黑名单(thinkphp 6.0.9/php 8.0.14)
2024-04-04 10:42:01407
一,创建一个middleware
liuhongdi@lhdpc:/data/php/admapi$ php think make:middleware CheckIp Middleware:app\middleware\CheckIp created successfully.
二,编写php代码
1, middleware/CheckIp.php
<?php
declare (strict_types = 1);
namespace app\middleware;
use app\result\Result;
class CheckIp
{
//地址列表,生产环境中通常会在redis中
private $ipList = ['192.168.219.1','127.0.0.2'];
/**
* 处理请求
*
* @param \think\Request $request
* @param \Closure $next
* @return Response
*/
public function handle($request, \Closure $next)
{
//得到当前IP
$ip = $request->ip();
//判断是否在列表中
if(in_array($ip,$this->ipList)){
return Result::Error(1,"IP地址错误");
}
return $next($request);
}
}2,middleware.php
<?php // 全局中间件定义文件 return [ // 全局请求缓存 // \think\middleware\CheckRequestCache::class, // 多语言加载 // \think\middleware\LoadLangPack::class, // Session初始化 // \think\middleware\SessionInit::class //调用对ip地址的检查 app\middleware\CheckIp::class, ];
3,result/Result.php
<?php
namespace app\result;
use think\response\Json;
class Result {
//success
static public function Success($data):Json {
$rs = [
'code'=>0,
'msg'=>"success",
'data'=>$data,
];
return json($rs);
}
//error
static public function Error($code,$msg):Json {
$rs = [
'code'=>$code,
'msg'=>$msg,
'data'=>"",
];
return json($rs);
}
}三,测试效果
1,当ip地址匹配时:
访问:
http://192.168.219.6:8000/article/onemedia?id=1
返回:
2,当ip地址不匹配时:
访问
http://127.0.0.1:8000/article/onemedia?id=1
