It is divided into three aspects: controller configuration, model rules configuration and view configuration.
Step one: Controller configuration
Configure the following code in actions, and the request verification code link corresponds to "controller/captcha".
'captcha' => [ 'class' => 'yii\captcha\CaptchaAction', // 'backColor'=>0x000000,//背景颜色 'maxLength' => 4, //最大显示个数 'minLength' => 4,//最少显示个数 'padding' => 5,//间距 'height'=>45,//高度 'width' => 75, //宽度 // 'foreColor'=>0xffffff, //字体颜色 'offset'=>4, ],
The second step: model rules configuration, that is, verify the configuration.
First declare the public variables
public $verifyCode
Secondly configure the verification in the rules method
['verifyCode', 'captcha','captchaAction'=>'user/captcha','on' => ['login']]
Add "captchaAction" in this configuration Configuration, that is, the routing of the controller. If not configured, the site/captcha routing will be used. This is the routing of the framework example.
Step Three: Configuration in the View
Add the following code to ActiveForm:
<?= $form->field($model,'verifyCode')->widget( Captcha::className(), [ 'template' => '{image}{input}', 'captchaAction'=>'user/captcha', // 此注意要使用自己配置的那个控制器验证码路由 'imageOptions'=>[ 'style'=>'cursor:pointer;width:77px'] ] )
Finally there is a huge pit problem : Due to the use of some newline characters or spaces under Windows during the encoding process, unknown output is caused and the verification code image cannot be generated normally.
This is the need to add the following code to the renderImageByGD method in the CaptchaAction class:
imagecolordeallocate($image, $foreColor); ob_clean(); // 此行为插入代码,目的是清空缓存区为输出图片提供干净空间。 ob_start(); imagepng($image); imagedestroy($image);
php Chinese website, a large number of free yii introductory tutorials, welcome to learn online!
The above is the detailed content of How to use yii's own verification code. For more information, please follow other related articles on the PHP Chinese website!