thinkphp6:使用路由中间件(php 8.1.1 / thinkphp v6.0.10LTS )
一,创建过滤IP的中间件
1,创建:
liuhongdi@lhdpc:/data/php/admapi$ php think make:middleware CheckIp Middleware:app\middleware\CheckIp created successfully.
2,代码:
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) { //echo "CheckIp:<br/>"; $ip = $request->ip(); if(in_array($ip,$this->ipList)){ return Result::Error(1,"IP地址错误"); } return $next($request); } }
说明:刘宏缔的架构森林是一个专注架构的博客,
网站:https://blog.imgtouch.com
本文: https://blog.imgtouch.com/index.php/2023/05/29/thinkphp6-shi-yong-lu-you-zhong-jian-jian-php-8-1-1/
对应的源码可以访问这里获取: https://github.com/liuhongdi/
或: https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,为路由指定中间件
1,route/app.php
<?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');
2,注意不要使CheckIp.php作为全局middleware
查看 app/middelware.php
<?php // 全局中间件定义文件 return [ app\middleware\CheckJwt::class, app\middleware\AdminLog::class, ];
三,测试效果
1,指定middleware时:
访问:
http://192.168.219.6:8000/article/qr
返回:
2,未指定middleware时:
访问:
http://192.168.219.6:8000/article/onemedia?id=1
返回:
四,查看php和thinkphp的版本:
php:
liuhongdi@lhdpc:/data/php/admapi$ php --version PHP 8.1.1 (cli) (built: Dec 20 2021 16:12:16) (NTS) Copyright (c) The PHP Group Zend Engine v4.1.1, Copyright (c) Zend Technologies with Zend OPcache v8.1.1, Copyright (c), by Zend Technologies
thinkphp:
liuhongdi@lhdpc:/var/www/html$ cd /data/php/admapi/ liuhongdi@lhdpc:/data/php/admapi$ php think version v6.0.10LTS