Yii框架验证码功能实现步骤详解
以下通过具体示例说明如何在Yii中生成和使用验证码,操作步骤如下。
首先,需要在SiteController的action方法中加入相关配置代码。
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',
),
);
二、(1)在LoginForm model rules()下添加代码: 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', ), ); //captche class needed array('verifyCode', 'captcha','allowEmpty'=>!CCaptcha::checkRequirements()), public $verifyCode; // verifyCode needs to be entered correctly array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
//captche class needed
array('verifyCode', 'captcha','allowEmpty'=>!CCaptcha::checkRequirements()),
接着,在LoginForm模型类内部声明对应的属性字段。
public $verifyCode;
此外,若需在其他表单中使用,需在ContactForm模型的rules()方法中进行类似配置。
// verifyCode needs to be entered correctly
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
最后,在登录页面的视图文件中添加用于显示和输入验证码的代码片段。
<?php
echo $form->labelEx($model,'verifyCode');
?>
<?php
$this->widget('CCaptcha');
?>
<?php
echo $form->textField($model,'verifyCode');
?>
<?php
echo $form->error($model,'verifyCode');
?>
上述代码仅展示核心功能,开发者可根据实际项目需求对程序进行扩展和优化,以提升实用性。