php 算术 验证码,php实现算术验证码的方法

这篇文章主要介绍了关于php实现算术验证码的方法,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下最近学了php的图像函数,也练习的验证码的实现,在听从老师的建议下,自己写了一个算术验证码的函数,第一次自己独立完成一个小练习,感觉挺开心的.但是,也知道自己的局限,所以特意写出来,希望各路大神指点一下,能够更多的拓展自己的视野

php代码如下:实现验证码的功能<?php /**

* @param int $width 宽度,默认为120

* @param int $height 高度,默认为50

* @param int $fontSize 字体的大小

* @return 图片资源

*/function arithmeticCode($width=120,$height=50,$fontSize=20){

//开启session

session_start(); //创建画布

$img = imagecreatetruecolor($width,$height); //分配颜色

$color = imagecolorallocate($img,255,255,255); //填充颜色

imagefill($img,0,0,$color); //干扰点

for ($i = 0;$i < 500;$i++){ $pixColor = imagecolorallocate($img,mt_rand(100,200),mt_rand(100,200),mt_rand(100,200));

imagesetpixel($img,mt_rand(0,$width),mt_rand(0,$height),$pixColor);

} //干扰线

for ($i = 0;$i < 4;$i++){ $lineColor = imagecolorallocate($img,mt_rand(0,120),mt_rand(0,120),mt_rand(0,120));

imageline($img,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width),mt_rand(0,$height),$lineColor);

} //定义一个数组存放运算符号

$arr = ['+','-','*']; //计算数组的长度

$len = count($arr); //定义一个1到20的数组

$num = range(1,20); $numLen = count($num); //定义一个空数组来存放随机取得的验证码

$code = []; for ($i = 0;$i < $len;$i++) { if ($i == 1) { $code[] = $arr[mt_rand(0,$len-1)];

}else { $code[] = $num[mt_rand(0,$numLen-1)];

}

} $str = implode($code);//将数组转为字符串

$textColor = imagecolorallocate($img,mt_rand(100,200),mt_rand(100,200),mt_rand(100,200)); $fontAngle = 0; $x = ($width - $fontSize*3)/2; $y = ($height - $fontSize) / 2 + $fontSize;

imagettftext($img,$fontSize,$fontAngle,$x,$y,$textColor,"./img/msyh.ttc",$str); $res = getRes($code); //将函数存放在session中

$_SESSION['res'] = $res; //输出图片

header("content-type:image/png");

imagepng($img);

}/**

* @param $arr 一个包含运算符号的数组

* @return 返回一个运算结果

*/function getRes($arr) {

$sum = 0; //判断数组元素下标为1的运算符号是什么

switch ($arr[1]){ case '+': $sum = $arr[0] + $arr[2]; break; case '-': $sum = $arr[0] - $arr[2]; break; case '*': $sum = $arr[0] * $arr[2]; break;

} return $sum;

}//调用函数arithmeticCode(100,40,18);

html的部分代码

content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">

Document

img { position: relative; top: 20px; }

验证码

点击刷新

提交

test.php的测试<?phpsession_start ();$res = $_SESSION['res'];$value = $_GET['code'];if ($res == $value) { echo "test success";

}else{ echo "test fail";

}

以上就是我的代码组成.

希望各路大神不吝赐教[期待脸]

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值