您的位置 首页 php

php验证码实现详解

今天做一个简单的信息收集功能,用到了表单,作为最最基本的防刷机制,验证码还是要有的,虽然不像12306网站那样有那么多人盯着,还是预防万一的。

习惯了框架php框架yii2 ,就用框架自带的验证码来实现吧,之前一直有人说yii的验证码有bug,也顺便验证一下。

图片验证码

验证码用到的action类是 yii\captcha\CaptchaAction

以下列出示例代码

1. controller 代码

class BusinessController extends Controller {

public function actions(){

return [

‘captcha’ => [

‘class’ => ‘yii\captcha\CaptchaAction’,

‘minLength’ => 4,

‘maxLength’ => 4

], //还有一些其他的参数,比如图片背景之类的

];

}

public function actionIndex(){

$model = new Contact();

if ($model->load(Yii::$app->request->post()) && $model-> validate ()) {

$rs = $model->save();

}

return $this->render(‘index’, [

‘model’ => $model

]);

}

}

2. model代码:

继承自 yii\db\ActiveRecord

class Contact extends ActiveRecord {

public $verifyCode;

public function rules() {

return [

……….

[‘verifyCode’, ‘captcha’, ‘captchaAction’=>’business/captcha’, ‘message’ => ‘{ attribute }错误’]

];

}

}

3. view代码:

use yii\bootstrap\ActiveForm;

use yii\captcha\Captcha;

<?php $form = ActiveForm::begin([‘id’ => ‘contact-form’]); ?>

。。。。。。。

<?= $form->field($model, ‘verifyCode’)->widget(Captcha::className(), [

‘captchaAction’=>’business/captcha’,

‘imageOptions’=>[‘id’=>’captchaimg’,’alt’=>’点击换图’,’title’=>’点击换图’, ‘style’=>’cursor:pointer’],

‘template’ => ‘<div class=”row”><div class=”col-lg-3″>{image}</div><div class=”col-lg-6″>{input}</div></div>’,

]) ?>

<?php ActiveForm::end(); ?>

4. 出现的一点小问题

在调试中发现验证码不正确,每次都是,查看源码的验证过程,

查看 yii\captcha\CaptchaAction

public function validate(),添加调试代码,把变量的值数出来

输出 session 验证码和用户输入的验证码

echo $input . ‘||’ . $code. ‘;’;

发现每次都是输出两次,第一次是正确的,第二次是错误的,这说明验证了两次,第一次验证成功后,看下面的代码,当验证成功是,$valid为TRUE,然后重新生成了验证码,所以第二次是错误的。

if ($valid || $session[$name] > $this->testLimit && $this->testLimit > 0) {

$this->getVerifyCode(true); //重新生成验证码

}

出问题的代码在controller中如下代码

if ($model->load(Yii::$app->request->post()) && $model->validate()) {

$rs = $model->save();

}

这里的validate()和save()都会验证一次,所以会出错.改正后的代码如下:

if ($model->load(Yii::$app->request->post()) && $rs = $model->save()) {

…….

}

点触验证码

5. 总结

验证码是网络安全最常用的验证措施之一,随着技术的发展,机器识别越来越厉害,最初的图片验证码也升级成了,最常见的类似于手机的滑动解锁拖动式验证码,还有12306点触式验证码等,随着网络安全的 攻防战,以后的验证码肯定也越来越智能,功能虽小但作用很大!

拖动验证码

文章来源:智云一二三科技

文章标题:php验证码实现详解

文章地址:https://www.zhihuclub.com/150301.shtml

关于作者: 智云科技

热门文章

网站地图