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 和 HTML
Oct 09 PHP
Snoopy类使用小例子
Apr 15 PHP
php学习笔记 PHP面向对象的程序设计
Jun 13 PHP
解析CI的AJAX分页 另类实现方法
Jun 27 PHP
php通过数组实现多条件查询实现方法(字符串分割)
May 06 PHP
ThinkPHP的L方法使用简介
Jun 18 PHP
php中in_array函数用法分析
Nov 15 PHP
thinkphp模板赋值与替换实例简述
Nov 24 PHP
linux下实现定时执行php脚本
Feb 13 PHP
分享一个Laravel好用的Cache宏
Mar 02 PHP
php限制上传文件类型并保存上传文件的方法
Mar 13 PHP
如何优雅的使用 laravel 的 validator验证方法
Nov 11 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
smtp邮件发送一例
2006/10/09 PHP
巧用php中的array_filter()函数去掉多维空值的代码分享
2012/09/07 PHP
PHP的PDO常用类库实例分析
2016/04/07 PHP
PHP写API输出的时用echo的原因详解
2019/04/28 PHP
javascript 面向对象全新理练之原型继承
2009/12/03 Javascript
ASP.NET中AJAX 调用实例代码
2012/05/03 Javascript
js动态添加表格数据使用insertRow和insertCell实现
2014/05/22 Javascript
javascript使用for循环批量注册的事件不能正确获取索引值的解决方法
2014/12/20 Javascript
使用JavaScript脚本无法直接改变Asp.net中Checkbox控件的Enable属性的解决方法
2015/09/16 Javascript
Bootstrap树形控件使用方法详解
2016/01/27 Javascript
bootstrap table动态加载数据示例代码
2017/03/25 Javascript
vue.js实现数据动态响应 Vue.set的简单应用
2017/06/15 Javascript
Angular4实现动态添加删除表单输入框功能
2017/08/11 Javascript
如何选择适合你的JavaScript框架
2017/11/20 Javascript
js登录滑动验证的实现(不滑动无法登陆)
2018/01/03 Javascript
vue 修改 data 数据问题并实时显示操作
2020/09/07 Javascript
vue 里面的 $forceUpdate() 强制实例重新渲染操作
2020/09/21 Javascript
python抓取网页内容示例分享
2014/02/24 Python
python基于itchat实现微信群消息同步机器人
2017/02/27 Python
Python多进程库multiprocessing中进程池Pool类的使用详解
2017/11/24 Python
详解Python中的分组函数groupby和itertools)
2018/07/11 Python
python应用文件读取与登录注册功能
2019/09/23 Python
Python 实现一行输入多个数字(用空格隔开)
2020/04/29 Python
速卖通欧盟:Aliexpress EU
2020/08/19 全球购物
交通专业个人自荐信格式
2013/09/23 职场文书
历史专业毕业生的自我鉴定
2013/11/15 职场文书
给同学的道歉信
2014/01/16 职场文书
大型晚会策划方案
2014/02/06 职场文书
毕业生简历自我评价范文
2014/04/09 职场文书
节能环保家庭事迹材料
2014/08/27 职场文书
2014大学生批评与自我批评思想汇报
2014/09/21 职场文书
学校元旦晚会开场白
2015/05/29 职场文书
优秀学生主要事迹怎么写
2015/11/04 职场文书
Golang表示枚举类型的详细讲解
2021/09/04 Golang
PostGIS的安装与入门使用指南
2022/01/18 PostgreSQL
Python first-order-model实现让照片动起来
2022/06/25 Python