🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 一,创建过滤IP的中间件 1,创建: ~~~ liuhongdi@lhdpc:/data/php/admapi$ php think make:middleware CheckIp Middleware:app\middleware\CheckIp created successfully. ~~~ 2,代码: middleware\\CheckIp.php [![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0); "复制代码") ~~~ <?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) { //echo "CheckIp:<br/>"; $ip = $request->ip(); if(in_array($ip,$this->ipList)){ return Result::Error(1,"IP地址错误"); } return $next($request); } } ~~~ [![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0); "复制代码") 说明:刘宏缔的架构森林是一个专注架构的博客,地址:[https://www.cnblogs.com/architectforest](https://www.cnblogs.com/architectforest)          对应的源码可以访问这里获取: [https://github.com/liuhongdi/ ](https://github.com/liuhongdi/)         或: [https://gitee.com/liuhongdi](https://gitee.com/liuhongdi) 说明:作者:刘宏缔 邮箱: 371125307@qq.com ## 二,为路由指定中间件 1,route/app.php [![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0); "复制代码") ~~~ <?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- use think\facade\Route; //Route::get('article/onemedia','article/oneMedia'); Route::group('article', function () { Route::get('onemedia', 'article/oneMedia'); Route::get('qr', 'article/qr')->middleware([\app\middleware\CheckIp::class]); //Route::miss('public/miss'); }); Route::miss('article/miss'); ~~~ [![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0); "复制代码") 2,注意不要使CheckIp.php作为全局middleware 查看 app/middelware.php [![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0); "复制代码") ~~~ <?php // 全局中间件定义文件 return [ app\middleware\CheckJwt::class, app\middleware\AdminLog::class, ]; ~~~ [![复制代码](https://common.cnblogs.com/images/copycode.gif)](javascript:void(0); "复制代码") ## 三,测试效果 1,指定middleware时: 访问: ~~~ http://192.168.219.6:8000/article/qr ~~~ 返回: ![](https://img.kancloud.cn/67/ce/67ce377065c2b02b807dcf894336654f_866x278.png) 2,未指定middleware时: 访问: ~~~ http://192.168.219.6:8000/article/onemedia?id=1 ~~~ 返回: ![](https://img.kancloud.cn/b2/f8/b2f8934aa5ee1501ce47f975fd75f07d_1184x594.png)