PHP验证码(带运算的)如何实现?

先从简单的说
1、绘制验证码图片:
我这里用GD2来实现的

先绘制画布

$im = imagecreate(66,18);//画布大小
$back = ImageColorAllocate($im, 245,245,245); //创建颜色
imagefill($im,0,0,$back); //把颜色填充到画布里

在画布上绘制数字

$font = ImageColorAllocate($im, rand(100,255),rand(0,100),rand(100,255)); //创建随机颜色
$s1=rand(1,9); //创建随机数字1-9
imagestring($im, 5, 2+0*10, 1, $s1, $font); // 在画布上绘制数字

到这里验证码基本绘制就完成了
如何加入加法运算?
原理是这样:绘制4个随机数字,第1个是被加数的十位,第2个是被加数的各位,第3个是被加数的十位,第4个是被加数的各位,然后在第2个数字和第3个数字之间绘制一个加好(+),在最后面绘制个等号(=)绘制功能就完成了。接下来算出结果,公式$scode=$s1*10+$s2+$s3*10+$s4,就是把十位上数字都乘以10然后再相加就可以了。
如何验证验证吗?
验证码在显示的时候我们把生成的结果存在一个session值里 $_SESSION['scode'] = $scode; 然后和用户输入的验证码做对比,这样就能知道用户输入的验证码是否正确。
以下是完整代码

<?php
session_start();
//生成验证码图片
Header("Content-type: image/PNG");
$im = imagecreate(66,18);
$back = ImageColorAllocate($im, 245,245,245);
imagefill($im,0,0,$back);
$scode=0;
srand((double)microtime()*1000000);
$font = ImageColorAllocate($im, rand(100,255),rand(0,100),rand(100,255));
$s1=rand(1,9);
imagestring($im, 5, 2+0*10, 1, $s1, $font);
$font = ImageColorAllocate($im, rand(100,255),rand(0,100),rand(100,255));
$s2=rand(1,9);
imagestring($im, 5, 2+1*10, 1, $s2, $font);
$font = ImageColorAllocate($im, rand(100,255),rand(0,100),rand(100,255));
imagestring($im, 5, 2+2*10, 1, '+', $font); 
$font = ImageColorAllocate($im, rand(100,255),rand(0,100),rand(100,255));
$s3=rand(1,9);
imagestring($im, 5, 2+3*10, 1, $s3, $font);
$font = ImageColorAllocate($im, rand(100,255),rand(0,100),rand(100,255));
$s4=rand(1,9);
imagestring($im, 5, 2+4*10, 1, $s4, $font);
$font = ImageColorAllocate($im, rand(100,255),rand(0,100),rand(100,255));
imagestring($im, 5, 2+5*10, 1, '=', $font); 
for($i=0;$i<100;$i++) //加入干扰象素
{
 $randcolor = ImageColorallocate($im,rand(0,255),rand(0,255),rand(0,255));
 imagesetpixel($im, rand()%70 , rand()%30 , $randcolor);
}
ImagePNG($im);
ImageDestroy($im);
$scode=$s1*10+$s2+$s3*10+$s4;
$_SESSION['scode'] = $scode;
?>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ganshenmail

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值