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 相关文章推荐
定制404错误页面,并发信给管理员的程序
Oct 09 PHP
利用static实现表格的颜色隔行显示
Oct 09 PHP
php实现首页链接查询 友情链接检查的代码
Jan 05 PHP
php 验证码实例代码
Jun 01 PHP
解析link_mysql的php版
Jun 30 PHP
PHP轻量级数据库操作类Medoo增加、删除、修改、查询例子
Jul 04 PHP
PH P5.2至5.5、5.6的新增功能详解
Jul 14 PHP
PHP缓存集成库phpFastCache用法
Dec 15 PHP
PHP编写daemon process详解及实例代码
Sep 30 PHP
PHP实现文件下载【实例分享】
Apr 28 PHP
laravel-admin的多级联动方法
Sep 30 PHP
Laravel实现搜索的时候分页并携带参数
Oct 15 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
PHP缓存技术的使用说明
2011/08/06 PHP
PHP检测字符串是否为UTF8编码的常用方法
2014/11/21 PHP
visual studio code 调试php方法(图文详解)
2017/09/15 PHP
PHP如何解决微信文章图片防盗链
2020/12/09 PHP
TextArea设置MaxLength属性最大输入值的js代码
2012/12/21 Javascript
表单验证的完整应用案例探讨
2013/03/29 Javascript
jQuery动画效果-slideUp slideDown上下滑动示例代码
2013/08/28 Javascript
JS限制文本框只能输入数字和字母方法
2015/02/28 Javascript
学习JavaScript设计模式之装饰者模式
2016/01/19 Javascript
微信小程序 video组件详解
2016/10/25 Javascript
javascript中Date对象的使用总结
2016/11/21 Javascript
详谈Node.js之操作文件系统
2017/08/29 Javascript
jQuery解析json格式数据示例
2018/09/01 jQuery
Element实现表格分页数据选择+全选所有完善批量操作
2019/06/07 Javascript
webpack5 联邦模块介绍详解
2020/07/08 Javascript
python使用os模块的os.walk遍历文件夹示例
2014/01/27 Python
Python实现遍历windows所有窗口并输出窗口标题的方法
2015/03/13 Python
Python中datetime模块参考手册
2017/01/13 Python
python抓取文件夹的所有文件
2018/02/27 Python
Pandas中把dataframe转成array的方法
2018/04/13 Python
使用Python实现一个栈判断括号是否平衡
2018/08/23 Python
基于python实现对文件进行切分行
2020/04/26 Python
使用SQLAlchemy操作数据库表过程解析
2020/06/10 Python
Python实现中英文全文搜索的示例
2020/12/04 Python
Toppik顶丰增发纤维官网:解决头发稀疏
2017/12/30 全球购物
英国美发和美容产品商城:HQhair
2019/02/08 全球购物
美国领先的眼镜和太阳镜在线零售商:Glasses.com
2019/08/26 全球购物
英语专业职业生涯规划范文
2014/03/05 职场文书
完整版商业计划书
2014/09/15 职场文书
大专毕业生自我鉴定范文(2篇)
2014/09/27 职场文书
社区务虚会发言材料
2014/10/20 职场文书
2015年党员创先争优承诺书
2015/01/22 职场文书
简历中自我评价范文
2015/03/11 职场文书
幼儿园元旦主持词
2015/07/06 职场文书
Java版 单机五子棋
2022/05/04 Java/Android
python 镜像环境搭建总结
2022/09/23 Python