PHP验证码(带运算的)如何实现?
2012-03-18 14:57
603 查看
先从简单的说
1、绘制验证码图片:
我这里用GD2来实现的
先绘制画布
在画布上绘制数字
到这里验证码基本绘制就完成了
如何加入加法运算?
原理是这样:绘制4个随机数字,第1个是被加数的十位,第2个是被加数的各位,第3个是被加数的十位,第4个是被加数的各位,然后在第2个数字和第3个数字之间绘制一个加好(+),在最后面绘制个等号(=)绘制功能就完成了。接下来算出结果,公式$scode=$s1*10+$s2+$s3*10+$s4,就是把十位上数字都乘以10然后再相加就可以了。
如何验证验证吗?
验证码在显示的时候我们把生成的结果存在一个session值里 $_SESSION['scode'] = $scode; 然后和用户输入的验证码做对比,这样就能知道用户输入的验证码是否正确。
以下是完整代码
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; ?>
相关文章推荐
- PHP如何实现验证码
- 教你php如何实现验证码
- PHP网站提交表单如何实现验证码验证功能
- 如何使用PHP中ci框架实现验证码?
- 二次开发-如何在PHPEMS引入第三方composer包-验证码实现!
- 教你php如何实现验证码
- 看PHP 如何实现变色验证码
- php实现的数字验证码及数字运算验证码
- php如何实现验证码
- php如何实现验证码
- php实现的数字验证码及数字运算验证码
- php 数学运算验证码实现代码
- php实现可运算的验证码
- 如何使用PHP中ci框架实现验证码?
- php 数学运算验证码实现代码
- php数字运算验证码的实现代码
- php实现可运算的验证码
- php如何实现验证码
- php数字运算验证码的实现代码
- 如何实现centos环境中的PHP JSON安装