laravel使用全局中间件记录请求日志,局部中间件检测登录实用案例

laravel中间件作用很大, 可以在请求过程中执行你前期所需要的操作。 比如session的判断,、请求日志的记录、 路径截取、IP记录等等

1.生成中间件

php artisan 创建中间件命令, laravel中有一个artisan 文件 创建文件目录:app\Http\Middleware

php artisan make:middleware WriteLogMiddleware(中间件名称)

2. 打开中间件类

$request方法查看

$request laravel对请求报文的


namespace App\Http\Middleware;

use Closure;

class WriteLogMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        file_put_contents('request.log',$request);
        file_put_contents('request.log',$request->path());
        return $next($request);
    }
}

常用方法:
$request->path() :路径
$request->ip() :IP地址
$request->server() :服务环境
$request->cookie() :cookie值

以下是日志写入request的请求报文

GET / HTTP/1.1
Accept:                    text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding:           gzip, deflate
Accept-Language:           zh-CN,zh;q=0.9
Connection:                keep-alive
Content-Length:            
Content-Type:              
Cookie:                    XSRF-TOKEN=eyJpdiI6ImpKeG9HenN5WWZ2bExqSmNoRkxpQlE9PSIsInZhbHVlIjoiMEdWamZmOVJveHVcLzlOczdcL0M2REZNRlh5WWd6VjdZbXZtMWhOQUN3OE9CS1h4eXp5OWI5MUFLTHR5TzdYYm5VdVljSUVjT1wvNjRkSjZqVXVoZ1pUbHc9PSIsIm1hYyI6IjI3OWM2ZWU4Njg0MGQzYjAzOTc5ZmFmZmUwMWZhOWM5YWFmNTc2YjhhN2Q1ZDhiMmVlNTM1ZjA4Y2Y5ZGJjMzMifQ%3D%3D; laravel_session=eyJpdiI6ImN6TXlZK2o1eVB5TjNvR2RIWTFySlE9PSIsInZhbHVlIjoiemdVczFBZ1doTlZUMGF0WTBWV1Y5V2F5WVcwc1d6aElKUE8rTUlJM3RlVnZ6NExaWUh1V3NUaDkzWmo3VVFuVnFTbk40akNvN3JWSmtmbTNweHNTZWc9PSIsIm1hYyI6IjY1OTFiNDI2ZmFiNDllOGM2MmU5Njk1NGNlOWMwOWZmMWRjYmExMzZhNDJmNGQzOGVjYWJjNjhkYWFlYzU5NTYifQ%3D%3D
Host:                      laravel.jx.com
Upgrade-Insecure-Requests: 1
User-Agent:                Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3719.400 QQBrowser/10.5.3715.400
Cookie: XSRF-TOKEN=sa9gaKhoXK1h2I2uM8YS1D1ijOnM6ONw8TL7BJjl; laravel_session=3a2efa81218298c3a4aadb626b113d6f5272aec0

3. 定义全局中间件

app\Http\Kernel.php 打开这个文件

这里面::class 是类常量不是静态方法

//Kernel.php
namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
		//在这定义 等同于:'\App\Http\Middleware\WriteLogMiddleware'
		\App\Http\Middleware\WriteLogMiddleware::class,
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    ];
}

注意 :如果不是全局中间件你要注册到 protected $routeMiddleware'别名' => \App\Http\Middleware\中间件类名::class,

示例:'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,

4. 路由中间件注册

  • 先使用命令创建中间件, 在写判断是否登录session。
namespace App\Http\Middleware;

use Closure;

class LoginMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!session('uid')) {
            return redirect('/login');
        }
        return $next($request);
    }
}

  • Kernel.php 注册中间件
//Kernel.php
namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
		//在这定义全局中间件 等同于:'\App\Http\Middleware\WriteLogMiddleware'
		\App\Http\Middleware\WriteLogMiddleware::class,
    ];

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        //在这定义路由中间件
        'login' => \App\Http\Middleware\LoginMiddleware::class,
    ];
}
  • 这里处理路由模块,包括绑定中间件

    Route::get('/login', function () {
        echo '登陆页面 ----------------';
        session(['uid'=>1]);//访问完就记录了session,再次访问setting就没有问题说明已经登录
    });

    Route::get('/setting', [
            'middleware' => 'login',//这里直接绑定了判断中间件
            'uses' => function () {
                echo '设置页面 -|||||||||||||';
            }
        ]
    );

你可能感兴趣的:(php)