登录功能,是我们几乎开发每个系统都必须的模块。
namespace app\index\controller;
use think\Controller;
class Login extends Controller
{
public function index()
{
return $this->fetch();
}
}
在 application\index\view 新建 login 文件夹,然后在其内新建 index.hml
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录系统title>
<link href="/static/bootstrap/css/bootstrap.min.css" rel="stylesheet">
head>
<body class="gray-bg">
<div class="container">
<div class="row">
<div class="col-sm-7">
<div class="ibox float-e-margins">
<div class="ibox-content">
<div class="row">
<div class="col-sm-6 b-r">
<h3 class="m-t-none m-b">登录h3>
<p>欢迎登录本站(⊙o⊙)p>
<form role="form" action="{:url('login/dologin')}" method="post">
<div class="form-group">
<label>用户名label>
<input type="text" placeholder="请输入用户名" class="form-control">
div>
<div class="form-group">
<label>密码label>
<input type="password" placeholder="请输入密码" class="form-control">
div>
<div>
<button class="btn btn-sm btn-primary pull-right m-t-n-xs" type="submit"><strong>登 录strong>
button>
div>
form>
div>
div>
div>
div>
div>
div>
div>
<script src="/static/js/jquery.min.js?v=2.1.4">script>
<script src="/static/bootstrap/js/bootstrap.min.js">script>
body>
html>
展示用户登陆的页面有了,那么我们现在来设计一下,存储用户信息的表。首先,我们通过 Navicat,新建一个 数据库 phper 并设计 编码为 UTF8,然后新建 用户表 users:
可以直接插入数据测试
下面我们就 可以用过这个 admin 进行后面的登录了。密码的 明文是 : admin.。然后我们配置一下 thinkphp5 的数据库设置。在application 下面的 database.php 进行的配置:
>[info] 配置这个数据库文件,那么前台模块 和 后台模块 都能用到这个数据库配置。同样,我们还可以在 admin 和 index 模块下面的 database.php 进行配置,这样可以单独对 index 和 admin 模块起作用。
// 数据库类型
'type' => 'mysql',
// 服务器地址
'hostname' => '127.0.0.1',
// 数据库名
'database' => '自己的数据库名',
// 用户名
'username' => 'root',
// 密码
'password' => '123456',
// 端口
'hostport' => '3306',
我们在页面设计的时候可以看到,我给 form 表单的提交地址填写的地址是 login控制的 dologin。因此,我们在 Login.php 中新建 doLogin 方法:
// 处理登录逻辑
public function doLogin()
{
$param = input('post.');
if(empty($param['user_name'])){
$this->error('用户名不能为空');
}
if(empty($param['user_pwd'])){
$this->error('密码不能为空');
}
// 验证用户名
$has = db('users')->where('user_name', $param['user_name'])->find();
if(empty($has)){
$this->error('用户名密码错误');
}
// 验证密码
if($has['user_pwd'] != md5($param['user_pwd'])){
$this->error('用户名密码错误');
}
// 记录用户登录信息
cookie('user_id', $has['id'], 3600); // 一个小时有效期
cookie('user_name', $has['user_name'], 3600);
$this->redirect(url('index/index'));
}
其中可以看到,登录成功之后,跳转到 index.php 的 index方法,下面我们设计一下 index.php 的 index 方法:
namespace app\index\controller;
class Index
{
public function index()
{
echo "您好: " . cookie('user_name') . ', 'login/loginout') . '">退出';
}
}
可见: 您好: admin, 退出
退出的设计逻辑,就是清除 cookie中的用户登录信息,跳转到登录页面即可。Login.php 的 loginOut 方法:
// 退出登录
public function loginOut()
{
cookie('user_id', null);
cookie('user_name', null);
$this->redirect(url('login/index'));
}
这样简单的登录就实现了