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

 更新时间:2017年05月20日 11:32:10   作者:molaifeng  
这篇文章主要介绍了Yii框架实现的验证码、登录及退出功能,结合具体实例形式分析了基于Yii框架实现的用户验证登录及退出操作相关步骤与操作技巧,需要的朋友可以参考下

本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

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

相关文章

  • 带密匙的php加密解密示例分享

    带密匙的php加密解密示例分享

    这篇文章主要介绍了php加密解密示例,大家参考使用吧
    2014-01-01
  • php操作memcache缓存方法分享

    php操作memcache缓存方法分享

    一般来说,如果并发量不大的情况,使不使用缓存技术并没有什么影响,但如果高并发的情况,使用缓存技术就显得很重要了,可以很好的减轻数据库和服务器的压力,当然解决高并发的技术有很多,这里只是以缓存的角度来说明使用memcache的便捷性和方便性,
    2015-06-06
  • PHP HTTP 认证实例详解

    PHP HTTP 认证实例详解

    这篇文章主要介绍了PHP HTTP 认证实例详解的相关资料,这里附有实现代码,及对认证的知识做一个详细的介绍说明,需要的朋友可以参考下
    2016-11-11
  • 详解php框架Yaf路由重写

    详解php框架Yaf路由重写

    这篇文章主要介绍了详解php框架Yaf路由重写,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-06-06
  • PHP 生成N个不重复的随机数

    PHP 生成N个不重复的随机数

    本文给大家展示的是一个实例,实用php实现了生产N个不同的随机数,实现思路和方法都介绍给了大家,小伙伴们参考下吧。
    2015-01-01
  • PHP上传文件参考配置大文件上传

    PHP上传文件参考配置大文件上传

    本文给大家介绍php上传文件参考配置大文件上传的相关知识,涉及到php上传文件配置的相关知识,对此感兴趣的朋友一起学习吧
    2015-12-12
  • 编写PHP程序检查字符串中的中文字符个数的实例分享

    编写PHP程序检查字符串中的中文字符个数的实例分享

    这篇文章主要介绍了编写PHP程序检查字符串中的中文字符个数的实例分享,文中利用了PHP中mb_strlen函数的实现原理,需要的朋友可以参考下
    2016-03-03
  • YII2框架中使用RBAC对模块,控制器,方法的权限控制及规则的使用示例

    YII2框架中使用RBAC对模块,控制器,方法的权限控制及规则的使用示例

    这篇文章主要介绍了YII2框架中使用RBAC对模块,控制器,方法的权限控制及规则的使用,结合实例形式分析了YII2框架RBAC对模块,控制器,方法的权限控制及规则的使用相关原理与操作技巧,需要的朋友可以参考下
    2020-03-03
  • Laravel框架表单验证详解

    Laravel框架表单验证详解

    这篇文章主要介绍了Laravel框架表单验证详解,本文给出了Laravel表单基本验证例子、高级使用方法、验证方法介绍等,要的朋友可以参考下
    2014-09-09
  • php判断页面是否是微信打开的示例(微信打开网页)

    php判断页面是否是微信打开的示例(微信打开网页)

    今天遇到一问题,让一个页面在微信上打开,PC上不能直接打开,下面是我使用的方法,现在分享给大家
    2014-04-04

最新评论