Yii框架实现的验证码、登录及退出功能示例


Posted in PHP onMay 20, 2017

本文实例讲述了Yii框架实现的验证码、登录及退出功能。分享给大家供大家参考,具体如下:

捣鼓了一下午,总算走通了,下面贴出代码。

Model

<?php
class Auth extends CActiveRecord {
  public static function model($className = __CLASS__) {
    return parent::model($className);
  }
  public function tableName() {
    return '{{auth}}';
  }
}

注:我的用户表是auth,所以模型是Auth.php

<?php
class IndexForm extends CFormModel {
  public $a_account;
  public $a_password;
  public $rememberMe;
  public $verifyCode;
  public $_identity;
  public function rules() {
    return array(
      array('verifyCode', 'captcha', 'allowEmpty' => !CCaptcha::checkRequirements(), 'message'=>'请输入正确的验证码'),
      array('a_account', 'required', 'message' => '用户名必填'),
      array('a_password', 'required', 'message' => '密码必填'),
      array('a_password', 'authenticate'),
      array('rememberMe', 'boolean'),
    );
  }
  public function authenticate($attribute, $params) {
    if (!$this->hasErrors()) {
      $this->_identity = new UserIdentity($this->a_account, $this->a_password);
      if (!$this->_identity->authenticate()) {
        $this->addError('a_password', '用户名或密码不存在');
      }
    }
  }
  public function login() {
    if ($this->_identity === null) {
      $this->_identity = new UserIdentity($this->a_account, $this->a_password);
      $this->_identity->authenticate();
    }
    if ($this->_identity->errorCode === UserIdentity::ERROR_NONE) {
      $duration = $this->rememberMe ? 60*60*24*7 : 0;
      Yii::app()->user->login($this->_identity, $duration);
      return true;
    } else {
      return false;
    }
  }
  public function attributeLabels() {
    return array(
      'a_account'   => '用户名',
      'a_password'   => '密码',
      'rememberMe'  => '记住登录状态',
      'verifyCode'  => '验证码'
    );
  }
}

注:IndexForm也可以写成LoginForm,只是系统内已经有了,我就没有替换它,同时注意看自己用户表的字段,一般是password和username,而我的是a_account和a_password

Controller

<?php
class IndexController extends Controller {
  public function actions() {
    return array(
      'captcha' => array(
        'class' => 'CCaptchaAction',
        'width'=>100,
        'height'=>50
      )
    );
  }
  public function actionLogin() {
    if (Yii::app()->user->id) {
      echo "<div>欢迎" . Yii::app()->user->id . ",<a href='" . SITE_URL . "admin/index/logout'>退出</a></div>";
    } else {
      $model = new IndexForm();
      if (isset($_POST['IndexForm'])) {
        $model->attributes = $_POST['IndexForm'];
        if ($model->validate() && $model->login()) {
          echo "<div>欢迎" . Yii::app()->user->id . ",<a href='" . SITE_URL . "admin/index/logout'>退出</a></div>";exit;
        }
      }
      $this->render('login', array('model' => $model));
    }
  }
  public function actionLogout() {
    Yii::app()->user->logout();
    $this->redirect(SITE_URL . 'admin/index/login');
  }
}

注:第一个方法是添加验证码的

view

<meta http-equiv="content-type" content="text/html;charset=utf-8">
<?php
$form = $this->beginWidget('CActiveForm', array(
  'id'            => 'login-form',
  'enableClientValidation'  => true,
  'clientOptions'       => array(
    'validateOnSubmit'   => true
  )
));
?>
  <div class="row">
    <?php echo $form->labelEx($model,'a_account'); ?>
    <?php echo $form->textField($model,'a_account'); ?>
    <?php echo $form->error($model,'a_account'); ?>
  </div>
  <div class="row">
    <?php echo $form->labelEx($model,'a_password'); ?>
    <?php echo $form->passwordField($model,'a_password'); ?>
    <?php echo $form->error($model,'a_password'); ?>
  </div>
  <?php if(CCaptcha::checkRequirements()) { ?>
  <div class="row">
    <?php echo $form->labelEx($model, 'verifyCode'); ?>
    <?php $this->widget('CCaptcha'); ?>
    <?php echo $form->textField($model, 'verifyCode'); ?>
    <?php echo $form->error($model, 'verifyCode'); ?>
  </div>
  <?php } ?>
  <div class="row rememberMe">
    <?php echo $form->checkBox($model,'rememberMe'); ?>
    <?php echo $form->label($model,'rememberMe'); ?>
    <?php echo $form->error($model,'rememberMe'); ?>
  </div>
  <div class="row buttons">
    <?php echo CHtml::submitButton('Submit'); ?>
  </div>
<?php $this->endWidget(); ?>

同时修改项目下protected/components下的UserIdentity.php

<?php
/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
  /**
   * Authenticates a user.
   * The example implementation makes sure if the username and password
   * are both 'demo'.
   * In practical applications, this should be changed to authenticate
   * against some persistent user identity storage (e.g. database).
   * @return boolean whether authentication succeeds.
   */
  public function authenticate()
  {
    /*
    $users=array(
      // username => password
      'demo'=>'demo',
      'admin'=>'admin',
    );
    if(!isset($users[$this->username]))
      $this->errorCode=self::ERROR_USERNAME_INVALID;
    elseif($users[$this->username]!==$this->password)
      $this->errorCode=self::ERROR_PASSWORD_INVALID;
    else
      $this->errorCode=self::ERROR_NONE;
    return !$this->errorCode;
    */
    $user_model = Auth::model()->find('a_account=:name',array(':name'=>$this->username));
    if($user_model === null){
      $this -> errorCode = self::ERROR_USERNAME_INVALID;
      return false;
    } else if ($user_model->a_password !== md5($this -> password)){
      $this->errorCode=self::ERROR_PASSWORD_INVALID;
      return false;
    } else {
      $this->errorCode=self::ERROR_NONE;
      return true;
    }
  }
}

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

PHP 相关文章推荐
利用文件属性结合Session实现在线人数统计
Oct 09 PHP
PHP扩展模块Pecl、Pear以及Perl的区别
Apr 09 PHP
PHP SOCKET编程详解
May 22 PHP
PHP.ini安全配置检测工具pcc简单介绍
Jul 02 PHP
PHP连接Nginx服务器并解析Nginx日志的方法
Aug 16 PHP
PHP的Laravel框架中使用消息队列queue及异步队列的方法
Mar 21 PHP
PHP简单操作MongoDB的方法(安装及增删改查)
May 26 PHP
在php7中MongoDB实现模糊查询的方法详解
May 03 PHP
PHP获取二叉树镜像的方法
Jan 17 PHP
PHP微商城开源代码实例
Mar 27 PHP
php的无刷新操作实现方法分析
Feb 28 PHP
PhpStorm 2020.3:新增开箱即用的PHP 8属性(推荐)
Oct 30 PHP
利用Laravel事件系统如何实现登录日志的记录详解
May 20 #PHP
Yii框架实现图片上传的方法详解
May 20 #PHP
Yii框架分页实现方法详解
May 20 #PHP
thinkPHP显示不出验证码的原因与解决方法分析
May 20 #PHP
yii2项目实战之restful api授权验证详解
May 20 #PHP
ThinkPHP下表单令牌错误与解决方法分析
May 20 #PHP
PHP那些琐碎的知识点(整理)
May 20 #PHP
You might like
PHP4实际应用经验篇(3)
2006/10/09 PHP
坏狼php学习 计数器实例代码
2008/06/15 PHP
ThinkPHP与PHPExcel冲突解决方法
2011/08/08 PHP
ThinkPHP中自定义错误页面和提示页面实例
2014/11/22 PHP
PHP两种实现无级递归分类的方法
2017/03/02 PHP
jquery 分页控件实现代码
2009/11/30 Javascript
jquery+css3打造一款ajax分页插件(自写)
2014/06/18 Javascript
jquery实现简单手风琴菜单效果实例
2015/06/13 Javascript
jquery利用拖拽方式在图片上添加热链接
2015/11/24 Javascript
JavaScript简单实现弹出拖拽窗口(二)
2016/06/17 Javascript
jQuery事件绑定方法学习总结(推荐)
2016/11/21 Javascript
vue使用axios实现文件上传进度的实时更新详解
2017/12/20 Javascript
jQuery实现合并表格单元格中相同行操作示例
2019/01/28 jQuery
新手入门js闭包学习过程解析
2019/10/08 Javascript
node.js使用yargs处理命令行参数操作示例
2020/02/11 Javascript
原生JavaScript之es6中Class的用法分析
2020/02/23 Javascript
微信小程序云函数添加数据到数据库的方法
2020/03/04 Javascript
JQuery通过键盘控制键盘按下与松开触发事件
2020/08/07 jQuery
[02:41]DOTA2英雄基础教程 冥魂大帝
2014/01/16 DOTA
[01:15:16]DOTA2-DPC中国联赛 正赛 Elephant vs Aster BO3 第一场 1月26日
2021/03/11 DOTA
Python getopt模块处理命令行选项实例
2014/05/13 Python
Python探索之SocketServer详解
2017/10/28 Python
详解python中sort排序使用
2019/03/23 Python
Python3多目标赋值及共享引用注意事项
2019/05/27 Python
Python2.7实现多进程下开发多线程示例
2019/05/31 Python
python tkinter组件摆放方式详解
2019/09/16 Python
python 实现表情识别
2020/11/21 Python
解决canvas转base64/jpeg时透明区域变成黑色背景的方法
2016/10/23 HTML / CSS
在校大学生的职业生涯规划书
2014/03/14 职场文书
秘书英文求职信
2014/04/16 职场文书
农村党员一句话承诺
2014/05/30 职场文书
2014年校长工作总结
2014/12/11 职场文书
学生个人评语大全
2015/01/04 职场文书
生活委员竞选稿
2015/11/21 职场文书
Python数据类型最全知识总结
2021/05/31 Python
基于JavaScript实现省市联动效果
2021/06/22 Javascript