laravel:使用全局中间件限制ip地址(10.27.0)
一,相关文档:
https://learnku.com/docs/laravel/10.x/middleware/14846
二,创建middleware
liuhongdi@lhdpc:/data/laravel/dignews$ php artisan make:middleware CheckIp
INFO Middleware [app/Http/Middleware/CheckIp.php] created successfully.
三,php代码
1,app/Http/Middleware/CheckIp.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; use App\extend\result\Result; class CheckIp { private $ipList = [ '192.168.219.1' , '127.0.0.2' ]; /** * Handle an incoming request. * * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next */ public function handle(Request $request , Closure $next ): Response { //得到当前IP $ip = $request ->ip(); //判断是否在列表中 if (in_array( $ip , $this ->ipList)){ return Result::ErrorCode(1, "IP地址错误:" . $ip ); } return $next ( $request ); } } |
2,注册到 app/Http/Kernel.php,使全局生效
在protected $middleware中添加我们的middleware,如下:
1
2
3
4
5
6
7
8
9
10
|
protected $middleware = [ // \App\Http\Middleware\TrustHosts::class, \App\Http\Middleware\TrustProxies:: class , \Illuminate\Http\Middleware\HandleCors:: class , \App\Http\Middleware\PreventRequestsDuringMaintenance:: class , \Illuminate\Foundation\Http\Middleware\ValidatePostSize:: class , \App\Http\Middleware\TrimStrings:: class , \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull:: class , \App\Http\Middleware\CheckIp:: class , ]; |
如图:
说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/10/17/laravel-shi-yong-quan-ju-zhong-jian-jian-xian-zhi-ip-di-zhi/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
四,测试效果
当我们的ip地址位于列表中时会报错:
五,查看laravel框架的版本:
liuhongdi@lhdpc:/data/laravel/dignews$ php artisan --version
Laravel Framework 10.27.0