Think php 5登陆注册session储存

目录结构:

数据库:

Login.php

<?php

namespace appindexcontroller;

use thinkController;
use thinkRequest;
use thinkSession;
use thinkDb;
use thinkView;

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

原文地址:https://www.cnblogs.com/zhumengyang/p/13346611.html