Home>

Model:

Add the verification code to a property of userlogin:

class userlogin extends cformmodel
{
 public $username;
 public $password;
 public $rememberme;
 public $verifycode;
 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"),   //verifycode needs to be entered correctly
   array ("verifycode", "captcha", "allowempty" =>! ccaptcha ::checkrequirements ()),  );
 }
 /**
  * declares attribute labels.
  * /
 public function attributelabels ()
 {
  return array (
   "rememberme" =>yii ::t ("user", "remember me next time"),   "username" =>yii ::t ("user", "username or email"),   "password" =>yii ::t ("user", "password"),   "verifycode" =>yy ::t ("user", "verification code"),  );
 }
}

Controller

Add mapping action ccaptchaaction in logincontroller controller

public function actions ()
{
 return array (
  //captcha action renders the captcha image displayed on the contact page
  "captcha" =>array (
   "class" =>"ccaptchaaction",   "backcolor" =>0xf4f4f4,   "padding" =>0,   "height" =>30,   "maxlength" =>4,  ),  );
}
ublic function actionlogin ()
{
 if (yii ::app ()->user->isguest) {
  $model=new userlogin;
  //collect user input data
  if (isset ($_ post ["userlogin"]))
  {
   $model->attributes=$_ post ["userlogin"];
//Check the verification code here
   if ($this->createaction ("captcha")->validate ($model->verifycode, false))
   {
    //validate user input and redirect to previous page if valid
    if ($model->validate ()) {
    //admin login only
    if (yii ::app ()->getmodule ("user")->isadmin () == 1)
    {
    $this->lastviset ();
    if (strpos (yii ::app ()->user->returnurl, "/index.php")! == false)
     $this->redirect (yii ::app ()->controller->module->returnurl);
    else
     $this->redirect (yii ::app ()->user->returnurl);
    } else
    {//if no admin when login out
     $this->redirect (yii ::app ()->controller->module->logouturl);
    }
   }
   } else
   {//Prompt error
    $model->adderror ("verifycode", "Wrong verification code");
   }
  }
  //display the login form
  $this->render ("/user/login", array ("model" =>$model));
 } else
  $this->redirect (yii ::app ()->controller->module->returnurl);
}

Before verifying the username and password,Check the verification code:

if ($this->createaction ("captcha")->validate ($model->verifycode, false))
{

3. view

Show captcha picture in view,Input box

<?php $this->widget ("ccaptcha");?>
  <?php echo chtml ::activetextfield ($model, "verifycode", array ("tabindex" =>1));?>
<img src="http://www.xxxx.net/uploads/123456.jpg">
php
  • Previous Waterfall layout with native JavaScript
  • Next C ++ implement genetic algorithm