ThinkPHP5.1中间件

1.安装中间件

php think make:middleware Check

2.中间件代码(application/http/middleware/Check)



namespace app\http\middleware;

use app\commit\Commit;
use app\index\model\DemoUser;
use think\Request;

class Check
{
     
    public function handle($request, \Closure $next)
    {
     
        $DemoUser=new DemoUser();
        $Commit=new Commit();
        if($request->header()){
     
            $AUTH = $request->header('auth');    //获取头信息
            $UserData=$Commit->AuthDe($AUTH);
            if(!$UserData){
     
                return redirect('/demo/public/index.php/middlewarteErr');
            }
            $Check=$DemoUser->where($UserData)->field('id')->find();
            if($Check){
     
                $request->user_id = $Check['id'];   //加入用户数据
            }else{
     
                return redirect('/demo/public/index.php/middlewarteErr');
            }
        }else{
     
            return redirect('/demo/public/index.php/middlewarteErr');
        }
        return $next($request);
    }
}

3.注册路由中间件

Route::rule('ce', 'index/Middleware.Middleware/ce')->middleware('Check');

你可能感兴趣的:(ThinkPHP)