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 相关文章推荐
PHP 中英文混合排版中处理字符串常用的函数
Apr 12 PHP
php 文件缓存函数
Oct 08 PHP
php 获取百度的热词数据的代码
Feb 18 PHP
phpmailer发送gmail邮件实例详解
Jun 24 PHP
php setcookie函数的参数说明及其用法
Apr 20 PHP
Thinkphp关闭缓存的方法
Jun 26 PHP
php通过会话控制实现身份验证实例
Oct 18 PHP
php mysql procedure实现获取多个结果集的方法【基于thinkPHP】
Nov 09 PHP
php安装php_rar扩展实现rar文件读取和解压的方法
Nov 17 PHP
php格式化时间戳
Dec 17 PHP
wordpress网站转移到本地运行测试的方法
Mar 15 PHP
PHP-FPM和Nginx的通信机制详解
Feb 01 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 安全检测代码片段(分享)
2013/07/05 PHP
PHP判断是否有Get参数的方法
2014/05/05 PHP
简单PHP会话(session)说明介绍
2016/08/21 PHP
php cli模式下获取参数的方法
2017/05/05 PHP
sina的lightbox效果。
2007/01/09 Javascript
JavaScript获得选中文本内容的方法
2008/12/02 Javascript
jquery中的sortable排序之后的保存状态的解决方法
2010/01/28 Javascript
js 禁用只读文本框获得焦点时的退格键
2010/04/25 Javascript
修改file按钮的默认样式实现代码
2013/04/23 Javascript
jquery移动点击的项目到列表最顶端的方法
2015/06/24 Javascript
基于javascript实现listbox左右移动
2016/01/29 Javascript
微信小程序 解决swiper不显示图片的方法
2017/01/04 Javascript
js如何获取网页所有图片
2017/05/12 Javascript
Node.js应用设置安全的沙箱环境
2018/04/23 Javascript
解决vant中 tab栏遇到的坑 van-tabs
2020/11/04 Javascript
Python标准库之Sys模块使用详解
2015/05/23 Python
Python将阿拉伯数字转换为罗马数字的方法
2015/07/10 Python
Windows下Eclipse+PyDev配置Python+PyQt4开发环境
2016/05/17 Python
python3制作捧腹网段子页爬虫
2017/02/12 Python
python cx_Oracle的基础使用方法(连接和增删改查)
2017/11/19 Python
详解Python的hasattr() getattr() setattr() 函数使用方法
2018/07/09 Python
解决pycharm的Python console不能调试当前程序的问题
2019/01/20 Python
CSS3 简单又实用的5个属性
2010/03/04 HTML / CSS
马来西亚网上购物:Youbeli
2018/03/30 全球购物
Hunkemöller西班牙:欧洲最大的内衣连锁店
2018/08/15 全球购物
韩国美国时尚服装和美容在线全球市场:KOODING
2018/11/07 全球购物
极度干燥澳大利亚官方网站:Superdry澳大利亚
2019/03/28 全球购物
Marc O’Polo俄罗斯官方在线商店:德国高端时尚品牌
2019/12/26 全球购物
JENNIFER BEHR官网:各种耳环和发饰
2020/06/07 全球购物
*p++ 自增p 还是p所指向的变量
2016/07/16 面试题
Tomcat的缺省是多少,怎么修改
2014/04/09 面试题
土木工程毕业生自荐信
2013/11/12 职场文书
校园网站的创业计划书范文
2013/12/30 职场文书
酒店总经理欢迎词
2014/01/08 职场文书
上班迟到检讨书
2014/09/15 职场文书
JS开发前端团队展示控制器来为成员引流
2022/08/14 Javascript