yii默认登录是admin和demo
首先要修改成用数据库中的user表进行登录
1.用gii生成user表的模型类User
2.重写protected/components/UserIdentity.php其中的authenticate()方法来实现我们自己的验证方法.具体代码如下:
<?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
{
private $_id;
public function authenticate()
{
// $user=User::model()->find('LOWER(username)=?',array(strtolower($this->username)));
$user=User::model()->find('LOWER(username)=:username',array(':username'=>strtolower($this->username)));
//echo $user->validatePassword($this->password);die;
if($user===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if(!$user->validatePassword($this->password))
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else{
$this->_id=$user->id;
$this->username=$user->username;
$this->errorCode=self::ERROR_NONE;
}
return $this->errorCode==self::ERROR_NONE;
}
public function getId()
{
return $this->_id;
}
}
3. protected/models/user.php中添加
<?php
public function validatePassword($password)
{
return $password===$this->password;
}
?>
4.登录时添加验证码
用yii新建项目后一般登录是在site模型内,所以
第一.在SiteController里添加方法actions
public function actions()
{
return array(
// captcha action renders the CAPTCHA image displayed on the contact page
//验证码配置
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
'maxLength'=>'4', // 最多生成几个字符
'minLength'=>'3', // 最少生成几个字符
'height'=>'30'
),
// page action renders "static" pages stored under 'protected/views/site/pages'
// They can be accessed via: index.php?r=site/page&view=FileName
'page'=>array(
'class'=>'CViewAction',
),
);
}
第二 我们需要在我们的formmodel中添加一个verifycode的属性来存放用户输入的验证码,然后通过captcha验证器来验证用户输入的验证码的准确性。
修改 protected\models\LoginFrom.php,添加
public $verifyCode;
并在rules中添加如下
public function rules()
{
return array(
// username and password are required
array('username, password,verifycode', 'required'),
// rememberMe needs to be a boolean
array('rememberMe', 'boolean'),
// password needs to be authenticated
array('password', 'authenticate'),
//下面是添加的验证码规则
array('verifycode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
);
}
第三在你的登录视图里面加上以下代码
<div class="row">
<?php echo "请输入验证码(<font color='red'>*</font>)</br>" ?>
<?php $this->widget('CCaptcha',array('showRefreshButton'=>false,'clickableImage'=>true,'imageOptions'=>array('alt'=>'点击换图','title'=>'点击换图','style'=>'cursor:pointer'))); ?>
<?php echo "<br>";?>
<?php echo $form->textField($model,'verifycode'); ?>
<?php echo $form->error($model,'verifycode'); ?>
</div>
第四解决刷新网页验证码不改变
<script>
$(document).ready(function(){
var img = new Image;
img.οnlοad=function(){
$('#yw0').trigger('click');
}
img.src = $('#yw0').attr('src');
});
</script>