通过使用ThinkPhp中间件来实现用户登录检测。
可以参考官网https://www.kancloud.cn/manual/thinkphp6_0/1037493
启用session
在app目录下,找到middleware.php。
<?php
// 全局中间件定义文件
return [
// 全局请求缓存
// \think\middleware\CheckRequestCache::class,
// 多语言加载
// \think\middleware\LoadLangPack::class,
// Session初始化
\think\middleware\SessionInit::class
];
把SessionInit的注释删除。
添加中间件
在你的项目根目录下
php think make:middleware Check
然后就会多一个文件夹middleware,下面有个Check.php,然后输入下面的代码
public function handle($request, \Closure $next)
{
if (Session::has("has_user")) {
return $next($request);
} else {
return redirect("login");
}
}
这边的'login'是在index中定义的。
执行这个中间件的时候,会去判断Session中是不是有'has_user'这个值,有的话表示用户登录过了,就让请求继续走下去,走到你要访问的地方。如果没有,表示用户没有登录,就重定向,去登录页面'login'
登录页面
先在view/index下面新建一个login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form method="post">
<div>
<input type="text" name="name" required="required">
</div>
<div>
<input type="password" name="password" required="required">
</div>
<input type="submit" name="login" value="Login">
</form>
</body>
</html>
在index.php中加入login
public function login()
{
if (Session::has("has_user")) {
return redirect("dashboard");
} else {
//Check login, when click 'login' submit button, will do this
if (isset($_REQUEST['login'])) {
$userName = isset($_REQUEST['name']) ? trim($_REQUEST['name']) : '';
$password = isset($_REQUEST['password']) ? trim($_REQUEST['password']) : '';
if ($userName == 'admin' && $password == '123') {
Session::set('has_user', $userName);
return redirect("dashboard");
} else {
echo "<script>alert('Error')</script>";
}
}
return View::fetch('login');
}
}
这边回去检测有没有用户登录过,有就继续访问,没有就去登录界面。
这边的dashboard就是我们加载的页面。
public function dashboard()
{
return View::fetch('index');
}
路由设置
Route::rule('login', 'index/login');
Route::group(function () {
Route::rule('dashboard', 'index/dashboard');
})->middleware(app\middleware\Check::class);
dashboard这个路由表示当你访问的时候,就会先去检查中间件,就是check.php,走handler,然后判断是否有登录。有就继续访问dashboard。没有就执行登录界面,index/login,判断是否登录,登录就走dashboard没有就显示login.html。
当你在登录界面点击提交的时候,页面应该会跳转,但是我们加了中间件,所以又走到了check.php,这样循环。知道登录了,才能访问dashboard。
重点:最好不要用默认的index/index,可能会有重定向的问题,所以我这边用了dashboard。