//首先生成4位验证码
//开启session
session_start();
//数组集合
$arr = array_merge(range(0,9),range('a','z'),range('A','Z'));
//打乱数组
shuffle($arr);
//截取4位验证码
$code = array_slice($arr,0,4);
//全部转为小写
$code = strtolower(join('',$code));
var_dump($code);
//将code存入session
$_SESSION['code'] = $code;
3. 开启GD库画图
//创建画布
$img = imagecreate(120,30);
//画布颜色
$white = imagecolorallocate($img,255,255,255);
//自定义集中颜色
$c1 = imagecolorallocate($img,14,38,54);
$c2 = imagecolorallocate($img,63,5,16);
$c3 = imagecolorallocate($img,248,248,42);
$c4 = imagecolorallocate($img,0,0,0);
//点干扰素
for ($i = 0;$i 300;$i++){
imagesetpixel($img,rand(0,120),rand(0,30),$c1);
}
//虚线干扰素
for($j = 0;$j 200;$j++){
imagedashedline($img,rand(0,120),rand(0,30),rand(0,120),rand(0,30),$c2);
}
//线干扰素
for ($j = 0;$j 10;$j++){
imageline($img,rand(0,120),rand(0,30),rand(0,120),rand(0,30),$c2);
}
//字体,这个你路径对了就OK
$font = "simhei.ttf";
//向图像写入文本
imagettftext($img,18,2,40,20,$c4,$font,$code);
//以jpg格式输出,还有以png啥的,imagepng这个自己看
imagejpeg($img);
//结束之后销毁,不销毁也行,php自带垃圾回收
imagedestroy($img);
?php
session_start();
print_r($_POST);
print_r($_SESSION['code']);
//如果提交的验证码跟session里面存的一样及认证成功
if($_POST['n3'] == $_SESSION['code']){
echo '注册成功';
}else{
echo '注册失败';
}
?>
!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>
/head>
body>
form action="" method="post">
input type="text" name="n1" placeholder="cc">
input type="text" name="n2" placeholder="s">
input type="text" name="n3">
!--这里点击刷新验证码 -->
img src="xxx.php" onclick="this.src='index.php?'+Math.random()" alt="">
input type="submit" value="submit">
/form>
/body>
/html>
搞定完事。到此这篇关于php结合GD库简单实现验证码的示例代码的文章就介绍到这了,更多相关php GD库验证码内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!