一,创建一个middleware
liuhongdi@lhdpc:/data/php/admapi$ php think make:middleware CheckIp Middleware:app\middleware\CheckIp created successfully.
说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest
对应的源码可以访问这里获取: https://github.com/liuhongdi/
或: https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,编写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返回:
四,查看php和thinkphp的版本:
php:root@lhdpc:~# php --version PHP 8.0.14 (cli) (built: Dec 23 2021 11:52:42) ( NTS ) Copyright (c) The PHP Group Zend Engine v4.0.14, Copyright (c) Zend Technologies with Zend OPcache v8.0.14, Copyright (c), by Zend Technologiesthinkphp:
root@lhdpc:~# cd /data/php/admapi/ root@lhdpc:/data/php/admapi# php think version v6.0.9