Phalcon之简易的登录功能

直接上代码:

Controllers\LogController:

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/13
 * Time: 17:53
 */
use Phalcon\Mvc\Controller;
    class LogController extends Controller{

        public function IndexAction(){

        }

        public function _registerSession($user){
            //设置Session
            $this->session->set(
                "auth",
                [
                    "name"     => $user->name,
                    "password" =>$user->password,
                ]
            );
        }

        public function StartAction(){

            //如果Session存在
            if($this->request->isPost()){

                $name     = $this->request->getPost("name");
                $password = $this->request->getPost("password");

                //查询数据库
                $conditions = 'name = :name: and password = :password:';
                $parameters = [

                    "name"    =>$name,
                    "password"=>$password,
                ];
                //查询数据库
                $ret = User::findFirst(
                    [
                        $conditions,
                        "bind"=>$parameters,
                    ]
                );
                if($ret){

                    $this->_registerSession($ret);
                    $this->flash->success(
                        "Welcom"." ".$ret->name
                    );
                }else{
                    $this->flash->error(
                        "用户名或密码错误"
                    );
                }
                //再一次跳转到登录界面
                $this->dispatcher->forward(
                    [
                        "controller" => "log",
                        "action"     => "index",
                    ]
                );
            }
        }
    }

views\log\index.phtml

<meta http-equiv="Content-Type" content="charset = utf-8"/>
<?php $this->flash->output();?>

<h2>欢迎登录</h2>
<?php echo $this->tag->form("../test/log/start")?>

<p>
    <label for="name">用户名</label>
    <?php echo $this->tag->textField("name") ?>
</p>

<p>
    <label for="password">密码</label>
    <?php echo $this->tag->textField("password")?>
</p>

<p>
    <?php echo $this->tag->submitButton("登录")?>
</p>

models\User.php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/5
 * Time: 9:42
 */
use\Phalcon\Mvc\Model;
    class User extends Model
    {
        public $id;
        public $name;
        public $email;
        public $password;
    }

数据库User表:



运行结果:

密码错误时提示用户名或密码错误:


密码正确时显示欢迎界面:

笔者水平有限,还会继续努力,请多多指教。




猜你喜欢

转载自blog.csdn.net/weixin_41800559/article/details/80002610