您的位置:首页 > 编程语言 > PHP开发

PHP生成简单计算的验证码,模仿CSDN

2015-11-03 15:30 597 查看
其实跟之前我发表的汉字验证码和英文单词加数字验证码差不多,只是多了一些逻辑的计算而已,我也是每次看到CSDN的这个验证码好奇,所以自己造了一个,大体看起来还不错,也比较符合日常的网站提交的验证。

代码如下:

<?php
if(!isset($_SESSION)){
session_start();
}
$image = imagecreatetruecolor(200, 60);
//设置验证码颜色 imagecolorallocate(int im, int red, int green, int blue);
$bgcolor = imagecolorallocate($image,255,255,255);
//区域填充 int imagefill(int im, int x, int y, int col)  (x,y) 所在的区域着色,col 表示欲涂上的颜色
imagefill($image, 0, 0, $bgcolor);
//设置  计算的数字和操作符号
$num = array('零','一','二','三','四','五','六','七','八','九');
//操作符号
$oper = array('+'=>'加','-'=>'减','*'=>'乘');
$fontface = 'simkai.ttf';
$fontcontent = $num[array_rand($num,1)].';';
$fontcontent.= $oper[array_rand($oper,1)].';';
$fontcontent.= $num[array_rand($num,1)].';';
$fontcontent.='等于?';
$arr = explode(';',$fontcontent);
for($i=0;$i<4;$i++){

//设置字体颜色,随机颜色 ,0-120深颜色
$fontcolor = imagecolorallocate($image, rand(0,120),rand(0,120), rand(0,120));
imagettftext($image, mt_rand(20,24),0,(30*$i+20),mt_rand(30,35),$fontcolor,$fontface,$arr[$i]);
}
$s_1 = array_keys($num,$arr[0]);
$s_2 = array_keys($oper,$arr[1]);
$s_3 = array_keys($num,$arr[2]);
//计算结果
switch($s_2[0]){

case '+':$ret = $s_1[0]+$s_3[0];break;
case '-':$ret = $s_1[0]-$s_3[0];break;
case '*':$ret = $s_1[0]*$s_3[0];break;

}
//存到session,作为提交表单的验证
$_SESSION['code'] = $ret;
//增加干扰元素,设置雪花点
for($i=0;$i<200;$i++){

//设置点的颜色,50-200颜色比数字浅,不干扰阅读
$pointcolor = imagecolorallocate($image,rand(50,200), rand(50,200), rand(50,200));
//imagesetpixel — 画一个单一像素
imagesetpixel($image, rand(1,199), rand(1,59), $pointcolor);
}
//设置头部,image/png
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
测试结果:





希望可以帮助到大家。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: