在index模块中,新建index控制器,该控制器主要实现 :
- 显示登录页面
- 实现登录时的身份验证
- 验证码的使用
- 会话管理session的使用
- 数据库的操作
- 页面跳转
- 退出登录
参考代码如下
<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Session;
/**
* Index 控制器
* 主要实现管理员登录,退出
*/
class Index extends Controller
{
//显示登录页面
public function index()
{
return $this->fetch();
}
//身份验证
public function dologin()
{
$user = input('post.username');
$pwd = input('post.password');
$vcode = input('post.vcode');
if (!captcha_check($vcode)) {
$this->error('验证码输入错误');
}
$data = Db::name('users')->where('user', $user)->where('password', $pwd)->find();
if (!$data) {
$this->error('用户名或密码错误');
}
Session::set('admin', $user);
$this->redirect('student/all');
}
//退出登录
public function logout()
{
Session::clear();
$this->redirect('index/index/index');
}
}
在dologin()方法中,有这样一个函数: captcha_check()它是tp5自带的一个助手函数,可以验证你输入的验证码是否正确
详见:tp5完全开发手册 “杂项-验证码-控制器验证”
有关数据库的操作
$data = Db::name('users')->where('user', $user)->where('password', $pwd)->find();表示从users数据表中查询记录,查询条件是user字段和password字段,使用find()查询和select()查询结果是不一样的
find()查询:返回一维数组,只有一条记录
select()查询:返回二维数组,可以有多条记录
详见:tp5完全开发手册“数据库-查询构造器-查询数据”
if (!$data) { $this->error('用户名或密码错误'); }使用find()方法,如果没有查到数据,返回null
此时证明:用户输入的帐户和密码是错误的
在dologin()方法中,有如下代码: Session::set('admin', $user);这是会话管理(session),在一般情况下,只要涉及登录,当登录成功后,我们会把登录的帐户保存在会话中
为什么使用会话管理,我们在学习php基础开发中,已经讲过了,如果还不清楚,可以参见:
https://blog.youkuaiyun.com/wang740209668/article/details/52787886
tp5框架把会话管理封装成了一个类Session,有关它的使用,可以参见 tp5完全开发手册“杂项-session”
logout()方法主要实现:
清除会话,使用指令:Session::clear();
跳转页面到登录页面: $this->redirect('index/index/index');

被折叠的 条评论
为什么被折叠?



