目錄結構:
數據庫:
Login.php
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\Session;
use think\Db;
use think\View;
class Login extends Controller
{
// 登錄頁面
public function demo()
{
// 判斷session中是否有用戶
if(session('username')){// 有 則進入首頁
return $this->redirect('/index/login/index');
}
// 跳轉登錄頁面
return $this->fetch('login/demo');
}
// 判斷登錄
public function login(){
//判斷是否是post方法發送的數據:如果是則開始登陸
if (Request::instance()->isPost()){
// 用戶名和密碼
$username = input('post.username');
$password = input('post.pwd');
if(empty($username) || empty($password)){
$this->error("用戶名或者密碼不能爲空!");
}
//從數據庫讀取數據 demo表
$res = DB::name('demo')
->where('username',$username)
->find();
// 判斷賬號密碼
if(empty($res)){
$this->error('用戶不存在,請重新登陸',url('Login/login'));
}else{
if($password!=$res['pwd']){
$this->error('密碼不正確,請重新登陸',url('Login/login'));
}else{
Session::set('username',$username);
$this->success("登錄成功!",url('login/index'));
}
}
}else{//如果不是post,則返回登陸界面
return view('login/demo');
}
}
// 首頁
public function index()
{
//是否有session
if(!session('username')){
return $this->error('請先登錄',url('login/demo'));
}
$view = new View();
$data = session('username');
$view->assign('data',$data);
return $view->fetch('login/index');
}
// 退出
public function logout(){
session(null);//退出清空session
return $this->success('退出成功',url('login/login'));//跳轉到登錄頁面
}
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>登錄成功</h1>
<h1>hello,{$data}</h1>
<h2>{$Request.session.user}</h2>
<a href="{:url('Login/logout')}">退出登陸</a>
</body>
</html>
demo.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="/index/login/login" method="post">
姓名: <input type="text" name="username"><br>
密碼: <input type="password" name="pwd"><br>
<input type="submit" value="登錄">
</form>
</body>
</html>
另外think php5 用命令行創建控制器鏈接:
https://blog.csdn.net/qq_40176206/article/details/93226239