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 Try Catch异常测试
Mar 01 PHP
php 将字符串按大写字母分隔成字符串数组
Apr 30 PHP
php连接数据库代码应用分析
May 29 PHP
phpmail类发送邮件函数代码
Feb 20 PHP
Linux系统下php获得系统分区信息的方法
Mar 30 PHP
PHP的伪随机数与真随机数详解
May 27 PHP
Apache服务器下防止图片盗链的办法
Jul 06 PHP
大家须知简单的php性能优化注意点
Jan 04 PHP
WordPress中调试缩略图的相关PHP函数使用解析
Jan 07 PHP
Zend Framework教程之资源(Resources)用法实例详解
Mar 14 PHP
PHP简单数据库操作类实例【支持增删改查及链式操作】
Oct 10 PHP
php实现给二维数组中所有一维数组添加值的方法
Feb 04 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
我的论坛源代码(八)
2006/10/09 PHP
php下的权限算法的实现
2007/04/28 PHP
php session 错误
2009/05/21 PHP
PHP 登录完成后如何跳转上一访问页面
2014/01/14 PHP
php使用SAE原生Mail类实现各种类型邮件发送的方法
2016/10/10 PHP
PHP十六进制颜色随机生成器功能示例
2017/07/24 PHP
phpwind放自动注册方法
2006/12/02 Javascript
Javascript 类与静态类的实现
2010/04/01 Javascript
浅析jquery的作用与优势
2013/12/02 Javascript
JS中操作JSON总结
2020/12/06 Javascript
jqeury-easyui-layout问题解决方法
2014/03/24 Javascript
jQuery 3.0 的变化及使用方法
2016/02/01 Javascript
基于BootStrap Metronic开发框架经验小结【六】对话框及提示框的处理和优化
2016/05/12 Javascript
JavaScript数组操作函数汇总
2016/08/05 Javascript
JS获取当前地理位置的方法
2017/10/25 Javascript
node 命令方式启动修改端口的方法
2018/05/12 Javascript
详解vue+webpack+express中间件接口使用
2018/07/17 Javascript
微信小程序自定义对话框弹出和隐藏动画
2018/07/19 Javascript
JavaScript函数重载操作实例浅析
2020/05/02 Javascript
[54:33]2018DOTA2亚洲邀请赛小组赛 A组加赛 Liquid vs Optic
2018/04/03 DOTA
python解析模块(ConfigParser)使用方法
2013/12/10 Python
python编程实现希尔排序
2017/04/13 Python
tensorflow训练中出现nan问题的解决
2018/02/10 Python
Python堆排序原理与实现方法详解
2018/05/11 Python
python库lxml在linux和WIN系统下的安装
2018/06/24 Python
用Django写天气预报查询网站
2018/10/21 Python
Django csrf 两种方法设置form的实例
2019/02/03 Python
python中bytes和str类型的区别
2019/10/21 Python
python读取csv文件指定行的2种方法详解
2020/02/13 Python
Python日志:自定义输出字段 json格式输出方式
2020/04/27 Python
python如何运行js语句
2020/09/09 Python
美国豪华时尚女性精品店:Kirna Zabête
2018/01/11 全球购物
产品售后服务承诺书
2014/05/21 职场文书
答谢酒会主持词
2015/07/02 职场文书
终止合同协议书范本
2016/03/22 职场文书
详解JS数组方法
2021/11/20 Javascript