Yii框架如何实现验证码、登录及退出功能

发布时间:2021-07-07 11:48:22 作者:小新
来源:亿速云 阅读:176

这篇文章给大家分享的是有关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框架如何实现验证码、登录及退出功能”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

推荐阅读:
  1. java中用servlet实现自动登录退出功能
  2. Spring Security实现验证码登录功能

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

yii框架

上一篇:Yii2怎么实现ActiveForm ajax提交

下一篇:Yii框架使用魔术方法怎么实现跨文件调用功能

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》