本篇文章为大家展示了使用php怎么实现一个算术验证码功能,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
php是一个嵌套的缩写名称,是英文超级文本预处理语言,它的语法混合了C、Java、Perl以及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的部分代码
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
img {
position: relative;
top: 20px;
}
</style>
</head>
<body>
<form action="test.php">
验证码 <input type="text" name="code">
<img src="./demo5.php" alt="点击刷新">
<br>
<button>提交</button>
</form>
</body>
</html>
<script>
//实现点击图片刷新验证码的功能
var img = document.querySelector("img");
img.onclick = function () {
this.src = this.src+"?m="+Math.random();
}
</script>
test.php的测试
<?php
session_start();
$res = $_SESSION['res'];
$value = $_GET['code'];
if ($res == $value) {
echo "test success";
}else{
echo "test fail";
}
上述内容就是使用php怎么实现一个算术验证码功能,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。