This yii tutorial is a little bit more difficult than other captcha tutorial.
The scenarios, after 3 unsuccessful login attempts, the captcha box appear. User must provide correct captcha to verify they are not machine.
Here is the way to make it.
Step 1:
We will add
verifyCode
attribute and add the
captchaEnable
in rule function
class LoginForm extends CFormModel { public $verifyCode; public function rules() { return array( array('username, password', 'required'), array('rememberMe', 'boolean'), array('password', 'authenticate'), array('verifyCode', 'captcha', 'allowEmpty' => !CCaptcha::checkRequirements(), 'on' => 'captchaEnable'), );
Step 2: Edit actionLogin in controller
public function actionLogin() { $model = new LoginForm; if (Yii::app()->user->getState('login_attempt') > 3) { <span style="color: #38761d;">//make the captcha required if the unsuccessful attemps are more of thee</span> $model->scenario = 'captchaEnable'; } if (isset($_POST['LoginForm'])) { $model->attributes = $_POST['LoginForm']; if ($model->validate() && $model->login()) { Yii::app()->user->setState('login_attempt', 0); <span style="color: #38761d;">//if login is successful, reset the attemps</span> $this->controller->redirect(Yii::app()->user->returnUrl); } else { <span style="color: #38761d;">//if login is not successful, increase the attemps </span> Yii::app()->user->setState('login_attempt', Yii::app()->user->getState('login_attempt', 0) + 1); if (Yii::app()->user->getState('login_attempt') > 3) { $model->scenario = 'captchaEnable'; <span style="color: #38761d;">//useful only for view</span> } } } $this->render('login', array('model' => $model)); }
Don’t forget to put yii captcha in
action()
function, if not, your application will not display captcha.
Step 3.
Add one more condition in yii view.
<?php if ($model->scenario == 'captchaEnable' && CCaptcha::checkRequirements()): ?>