前几日正好重温下GD库,来玩一下生成带有干扰素的验证码。

生成字母数字的图片验证码

  1. 首先需要看php.ini配置文件中有没有GD库,如果没有开启,请自行开启下,我用的小皮面板,基本现在都给你带上了。
  2. 需要生成4位(位数自定)验证码
//首先生成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库画图
注意一下这个imagecolorallocate函数

//创建画布
$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);

  1. 前台的展示
<?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>

搞定完事,下一次写一下中文的验证码,看到这希望大佬们动动小手点个赞吧~

本文地址:https://blog.csdn.net/weixin_44088587/article/details/112215442