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查询域名状态whois的类
Nov 25 PHP
php radio 单选框获取与保持值的实现代码
May 15 PHP
php后退一页表单内容保存实现方法
Jun 17 PHP
深入PHP FTP类的详解
Jun 13 PHP
php增删改查示例自己写的demo
Sep 04 PHP
PHP中VC6、VC9、TS、NTS版本的区别与用法详解
Oct 26 PHP
php实例分享之通过递归实现删除目录下的所有文件详解
May 15 PHP
PHP mkdir()无写权限的问题解决方法
Jun 19 PHP
PHP中SERIALIZE和JSON的序列化与反序列化操作区别分析
Oct 11 PHP
php实现的二分查找算法示例
Jun 20 PHP
基于 Swoole 的微信扫码登录功能实现代码
Jan 15 PHP
PHP date_default_timezone_set()设置时区操作实例分析
May 16 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
thinkphp实现附件上传功能
2017/05/26 PHP
PHP实现双链表删除与插入节点的方法示例
2017/11/11 PHP
PHP保留两位小数的几种方法
2019/07/24 PHP
php提供实现反射的方法和实例代码
2019/09/17 PHP
如何获取select下拉框的值(option没有及有value属性)
2013/11/08 Javascript
JavaScript中使用ActiveXObject操作本地文件夹的方法
2014/03/28 Javascript
nodejs实现遍历文件夹并统计文件大小
2015/05/28 NodeJs
基于jquery实现轮播特效
2016/04/22 Javascript
全面解析多种Bootstrap图片轮播效果
2016/05/27 Javascript
详解JSON1:使用TSQL查询数据和更新JSON数据
2016/11/21 Javascript
javascript 利用arguments实现可变长参数
2016/11/21 Javascript
Javascript 实现放大镜效果实例详解
2016/12/03 Javascript
详解nodejs微信公众号开发——5.素材管理接口
2017/04/11 NodeJs
jquery实现放大镜简洁代码(推荐)
2017/06/08 jQuery
详解React 在服务端渲染的实现
2017/11/16 Javascript
layui加载数据显示loading加载完成loading消失的实例代码
2019/09/23 Javascript
JavaScript使用百度ECharts插件绘制饼图操作示例
2019/11/26 Javascript
Windows系统下安装Python的SSH模块教程
2015/02/05 Python
Python计算三角函数之asin()方法的使用
2015/05/15 Python
两个使用Python脚本操作文件的小示例分享
2015/08/27 Python
Python和Java进行DES加密和解密的实例
2018/01/09 Python
初探TensorFLow从文件读取图片的四种方式
2018/02/06 Python
Python脚本按照当前日期创建多级目录
2019/03/01 Python
使用PyQt4 设置TextEdit背景的方法
2019/06/14 Python
python中有关时间日期格式转换问题
2019/12/25 Python
django在保存图像的同时压缩图像示例代码详解
2020/02/11 Python
Python使用qrcode二维码库生成二维码方法详解
2020/02/17 Python
Django获取model中的字段名和字段的verbose_name方式
2020/05/19 Python
解决Pycharm 运行后没有输出的问题
2021/02/05 Python
美国摄影爱好者购物网站:Focus Camera
2016/10/21 全球购物
证婚人经典证婚词
2014/01/09 职场文书
项目经理聘任书
2014/03/29 职场文书
邀请函模板
2015/02/02 职场文书
女性健康知识讲座主持词
2015/07/04 职场文书
2016继续教育培训学习心得体会
2016/01/19 职场文书
python树莓派通过队列实现进程交互的程序分析
2021/07/04 Python