Fork me on GitHub

标签 captcha 下的文章

在Yii中使用Captcha验证码

在Yii自带demo里,site/contact中使用了验证码,用法如下

Controller

在SiteController加入映射动作CCaptchaAction,映射到SiteController的目的是获取验证码图片,以及表单校验都会用到这个action的类,因为Yii的验证码的session_key是根据controller生成的(也就是说每个controller的验证码的session_key都不同),所以验证码的生成与验证必须在同一个controller中进行。

    /**
     * Declares class-based actions.
     */
    public function actions()
    {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha'=>array(
                'class'=>'CCaptchaAction',
                'backColor'=>0xFFFFFF,
            ),
            // 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',
            ),
        );
    }
     
    /**
     * Displays the contact page
     */
    public function actionContact()
    {
        $model=new ContactForm;
        if(isset($_POST['ContactForm']))
        {
            $model->attributes=$_POST['ContactForm'];
            if($model->validate())
            {
                $name='=?UTF-8?B?'.base64_encode($model->name).'?=';
                $subject='=?UTF-8?B?'.base64_encode($model->subject).'?=';
                $headers="From: $name <{$model->email}>

".
                    "Reply-To: {$model->email}

".
                    "MIME-Version: 1.0

".
                    "Content-Type: text/plain; charset=UTF-8";
 
                mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers);
                Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
                $this->refresh();
            }
        }
        $this->render('contact',array('model'=>$model));
    }

Model

将验证码属性添加到model里,并设置验证方法,这样调用model的验证方法时将自动验证验证码是否正确

    //验证码
    public $verifyCode;
 
    /**
     * 定义验证规则
     */
    public function rules()
    {
        return array(
            // name, email, subject and body are required
            array('name, email, subject, body', 'required'),
            ...
            //验证码验证规则
            array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
        );
    }

View

上面两个步骤完成后,就可以在view里加载小部件了

<div class="captcha_box">    
    <?php $this->widget('CCaptcha'); ?>
    <?php echo $form->textField($model,'verifyCode'); ?>
</div>

这样就可以在提交表单的时候使用验证码了