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版(5)
Oct 09 PHP
PHP 替换模板变量实现步骤
Aug 24 PHP
PHP排序之二维数组的按照字母排序实现代码
Aug 13 PHP
PHP set_error_handler()函数使用详解(示例)
Nov 12 PHP
PHP中的reflection反射机制测试例子
Aug 05 PHP
THINKPHP截取中文字符串函数实例代码
Mar 20 PHP
PHP如何搭建百度Ueditor富文本编辑器
Sep 21 PHP
PHP中Static(静态)关键字功能与用法实例分析
Apr 05 PHP
php使用yield对性能提升的测试实例分析
Sep 19 PHP
php设计模式之工厂模式用法经典实例分析
Sep 20 PHP
php 函数中静态变量使用的问题实例分析
Mar 05 PHP
浅谈如何提高PHP代码质量之端到端集成测试
May 28 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
php的memcache类分享(memcache队列)
2014/03/26 PHP
简单谈谈php延迟静态绑定
2016/01/26 PHP
php微信公众平台示例代码分析(二)
2016/12/06 PHP
JS时间选择器 兼容IE6,7,8,9
2012/06/26 Javascript
jQuery中校验时间格式的正则表达式小结
2013/09/22 Javascript
js转义字符介绍
2013/11/05 Javascript
JS获得QQ号码的昵称,头像,生日的简单实例
2013/12/04 Javascript
JavaScript中的迭代器和生成器详解
2014/10/29 Javascript
深入分析Javascript跨域问题
2015/04/17 Javascript
jQuery实现冻结表格行和列
2015/04/29 Javascript
如何根据百度地图计算出两地之间的驾驶距离(两种语言js和C#)
2015/10/29 Javascript
React如何利用相对于根目录进行引用组件详解
2017/10/09 Javascript
AngularJS 实现购物车全选反选功能
2017/10/24 Javascript
解决VUEX兼容IE上的报错问题
2018/03/01 Javascript
Vue.js 踩坑记之双向绑定
2018/05/03 Javascript
解决vue中修改了数据但视图无法更新的情况
2018/08/27 Javascript
如何在Angular8.0下使用ngx-translate进行国际化配置
2019/07/24 Javascript
vue + elementUI实现省市县三级联动的方法示例
2019/10/29 Javascript
Vue解决echart在element的tab切换时显示不正确问题
2020/08/03 Javascript
用Python实现服务器中只重载被修改的进程的方法
2015/04/30 Python
读取本地json文件,解析json(实例讲解)
2017/12/06 Python
centos 安装python3.6环境并配置虚拟环境的详细教程
2018/02/22 Python
Python爬虫框架scrapy实现的文件下载功能示例
2018/08/04 Python
python 统计一个列表当中的每一个元素出现了多少次的方法
2018/11/14 Python
Python OpenCV中的resize()函数的使用
2019/06/20 Python
Python使用正则表达式实现爬虫数据抽取
2020/08/17 Python
全面解析HTML5中的标准属性与自定义属性
2016/02/18 HTML / CSS
Square Off美国/加拿大:世界上最聪明的国际象棋棋盘
2018/12/06 全球购物
行政人事经理职位说明书
2014/03/05 职场文书
《窗前的气球》教学反思
2014/04/07 职场文书
产品陈列协议书(标准版)
2014/09/17 职场文书
小学教师师德整改措施
2014/09/29 职场文书
教师政风行风评议心得体会
2014/10/21 职场文书
医药公司开票员岗位职责
2015/04/15 职场文书
2016春节放假通知范文
2015/08/18 职场文书
Android超详细讲解组件ScrollView的使用
2022/03/31 Java/Android