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 输出双引号&quot;与单引号'的方法
May 09 PHP
PHP Cookie的使用教程详解
Jun 03 PHP
PHP判断变量是否为0的方法
Feb 08 PHP
php密码生成类实例
Sep 24 PHP
Linux下安装PHP MSSQL扩展教程
Oct 24 PHP
php实现将任意进制数转换成10进制的方法
Apr 17 PHP
PHP中Laravel 关联查询返回错误id的解决方法
Apr 01 PHP
PHP使用preg_split和explode分割textarea存放内容的方法分析
Jul 03 PHP
Laravel 实现密码重置功能
Feb 23 PHP
PHP中如何使用Redis接管文件存储Session详解
Nov 28 PHP
php session_decode函数用法讲解
May 26 PHP
Nginx+php配置文件及原理解析
Dec 09 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
多重?l件?合查?(二)
2006/10/09 PHP
php禁止浏览器使用缓存页面的方法
2014/11/07 PHP
php中动态变量用法实例
2015/06/10 PHP
php获取一定范围内取N个不重复的随机数
2016/05/28 PHP
Yii CDBCriteria常用方法实例小结
2017/01/19 PHP
学习thinkphp5.0验证类使用方法
2017/11/16 PHP
Laravel框架FormRequest中重写错误处理的方法
2019/02/18 PHP
微信公众平台开发教程⑥ 微信开发集成类的使用图文详解
2019/04/10 PHP
PHP的HTTP客户端Guzzle简单使用方法分析
2019/10/30 PHP
JQuery模板插件 jquery.tmpl 动态ajax扩展
2011/11/10 Javascript
jquery拖动插件(jquery.drag)使用介绍
2013/06/18 Javascript
javascript实现焦点滚动图效果 具体方法
2013/06/24 Javascript
jQuery中bind与live的用法及区别小结
2014/01/27 Javascript
PHPMyAdmin导入时提示文件大小超出PHP限制的解决方法
2015/03/30 Javascript
详解AngularJS中的作用域
2015/06/17 Javascript
javascript制作幻灯片(360度全景图片)
2015/07/28 Javascript
jQuery延迟执行的实现方法
2016/12/21 Javascript
自定义vue全局组件use使用、vuex的使用详解
2017/06/14 Javascript
import与export在node.js中的使用详解
2017/09/28 Javascript
Node.js中DNS模块学习总结
2018/02/28 Javascript
vue-cli 打包后提交到线上出现 &quot;Uncaught SyntaxError:Unexpected token&quot; 报错
2018/11/06 Javascript
详解如何模拟实现node中的Events模块(通俗易懂版)
2019/04/15 Javascript
[06:07]DOTA2-DPC中国联赛3月5日Recap集锦
2021/03/11 DOTA
利用一个简单的例子窥探CPython内核的运行机制
2015/03/30 Python
Python3实现计算两个数组的交集算法示例
2019/04/03 Python
Django REST Framework之频率限制的使用
2019/09/29 Python
详解Django配置JWT认证方式
2020/05/09 Python
html5 跨文档消息传输示例探讨
2013/04/01 HTML / CSS
耐克巴西官方网站:Nike巴西
2016/08/14 全球购物
如何实现一个自定义类的序列化
2012/05/22 面试题
机械工程师求职自我评价
2013/09/23 职场文书
服务员自我评价
2014/01/25 职场文书
学习十八大报告感言
2014/02/28 职场文书
治超工作实施方案
2014/05/04 职场文书
教师求职自荐信
2015/03/26 职场文书
委托开发合同书(标准版)
2019/08/07 职场文书