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

 更新时间:2017年5月26日 22:11  点击:1599

本文实例讲述了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程序设计有所帮助。

[!--infotagslink--]

相关文章

  • 基于JavaScript实现验证码功能

    这篇文章主要介绍了基于JavaScript实现验证码功能的相关资料...2017-04-03
  • Bootstrap中文本框的宽度变窄并且加入一副验证码图片的实现方法

    这篇文章主要介绍了Bootstrap中文本框的宽度变窄并且加入一副验证码图片的实现方法的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下...2016-06-24
  • Web制作验证码功能实例代码

    web开发中,经常会使用验证码功能,例如登录、注册,或其他关键功能之前经常会使用。下面通过实例代码给大家介绍Web制作验证码功能实例代码,感兴趣的朋友一起看看吧...2017-06-24
  • 利用Yii框架实现图片上传

    这篇文章主要介绍了Yii框架实现图片上传的方法,结合实例形式较为详细的分析了Yii框架实现图片上传功能的具体步骤与相关操作技巧,需要的朋友可以参考下 本文实例...2017-07-06
  • PHP实现QQ登录实例代码

    分享一段利用PHP实现QQ登陆的代码,原理是用curl模拟发送post登录,cookie保存本地,实现真正的3GQQ登陆,对php实现qq登录相关知识感兴趣的朋友一起学习吧...2016-01-16
  • Yii框架实现邮箱激活的方法【数字签名】

    这篇文章主要介绍了Yii框架实现邮箱激活的方法,基于邮箱发送邮件实现数字签名的激活功能,需要的朋友可以参考下...2016-10-20
  • js微信扫描二维码登录网站技术原理

    这篇文章主要介绍了js微信扫描二维码登录网站技术原理,具有一定的参考价值,有需要的可以了解一下。...2016-12-02
  • jquery实现无刷新验证码的简单实例

    下面小编就为大家带来一篇jquery实现无刷新验证码的简单实例。小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2016-05-20
  • MySQL基于DOS命令行登录操作实例(图文说明) 原创

    这篇文章主要介绍了MySQL基于DOS命令行登录操作,以图文形式结合实例说明了MySQL登录命令的基本用法,非常简单易懂需要的朋友可以参考下...2016-01-15
  • PHP实现登陆表单提交CSRF及验证码

    本文主要介绍了PHP实现登陆表单提交CSRF及验证码的方法。具有很好的参考价值,下面跟着小编一起来看下吧...2017-02-09
  • PHP+Ajax实现验证码的实时验证

    这篇文章主要为大家详细介绍了PHP+Ajax实现验证码的实时验证,感兴趣的小伙伴们可以参考一下...2016-07-29
  • 基于JavaScript短信验证码如何实现

    我们在使用移动、电信等运营商网上营业厅的时候,为确保业务的完整和正确性,经常会需要用到短信的验证码。最近因为某省业务需要,也做了个类似的功能...2016-01-25
  • laravel5.2实现区分前后台用户登录的方法

    这篇文章主要介绍了laravel5.2实现区分前后台用户登录的方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下...2017-01-15
  • php bootstrap实现简单登录

    这篇文章主要为大家详细介绍了php bootstrap实现简单登录的具体方法,感兴趣的小伙伴们可以参考一下...2016-03-10
  • 一个简单安全的PHP验证码类 附调用方法

    这篇文章主要为大家分享了一个简单安全的PHP验证码类,附调用方法,感兴趣的小伙伴们可以参考一下...2016-07-02
  • js实现随机数字字母验证码

    这篇文章主要为大家详细介绍了js随机验证码的实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2017-06-24
  • php图像验证码生成代码

    这篇文章主要为大家详细 介绍了php图像验证码的生成代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2017-06-11
  • php+MySQL实现登录时验证登录名和密码是否正确

    本文实例实现登录时去数据库校验用户输入的登录名和密码是否正确,这篇文章主要介绍了php+MySQL实现登录时校验登录名和密码是否正确,感兴趣的小伙伴们可以参考一下...2016-05-13
  • Yii框架批量插入数据扩展类的简单实现方法

    这篇文章主要介绍了Yii框架批量插入数据扩展类的简单实现方法,涉及Yii扩展类及数据库相关操作技巧,需要的朋友可以参考下...2017-05-26
  • php生成酷炫的四个字符验证码

    可以生成随机颜色、干扰线条元素、干扰点元素的php验证码,这篇文章主要介绍了php生成酷炫的四个字符验证码的编写方法,感兴趣的小伙伴们可以参考一下...2016-04-23