温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在php中使用GD库实现一个验证码功能

发布时间:2021-02-04 17:15:47 来源:亿速云 阅读:110 作者:Leah 栏目:开发技术

今天就跟大家聊聊有关如何在php中使用GD库实现一个验证码功能,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

具体实现:

<?php/*PHP实现验证码*/
session_start();//开启会话
//创建画布
$image=imagecreatetruecolor(100,38);
//背景颜色
$bgcolor=imagecolorallocate($image,255,255,255);
imagefill($image,0,0,$bgcolor);
$captch_code='';//存储验证码
//随机选取4个数字
for($i=0;$i<4;$i++){
 $fontsize=10;  //
 $fontcolor=imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120));//随机颜色
 $fontcontent=rand(0,9);
 $captch_code.=$fontcontent;
 $x=($i*100/4)+rand(5,10); //随机坐标
 $y=rand(5,10);
 imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor);
}
/*//字母和数字混合验证码
for($i=0;$i<4;$i++) {
 $fontsize = 10;  //
 $fontcolor = imagecolorallocate($image, rand(0, 120), rand(0, 120), rand(0, 120));//??????
 $data = 'abcdefghijklmnopqrstuvwxyz1234567890'; //数据字典
 $fontcontent = substr($data, rand(0, strlen($data)), 1);
 $captch_code.=$fontcontent;
 $x = ($i * 100 / 4) + rand(5, 10);
 $y = rand(5, 10);
 imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);
}*/
$_SESSION['code']=$captch_code;
//增加干扰点
for($i=0;$i<200;$i++){
 $pointcolor=imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200));
 imagesetpixel($image,rand(1,99),rand(1,29),$pointcolor);//
}
//增加干扰线
for($i=0;$i<3;$i++){
 $linecolor=imagecolorallocate($image,rand(80,280),rand(80,220),rand(80,220));
 imageline($image,rand(1,99),rand(1,29),rand(1,99),rand(1,29),$linecolor);
}
//输出格式
header('content-type:image.png');
imagepng($image);
//销毁图片
imagedestroy($image);

实现表单的连接和“换一个”功能的实现:1

<input type="text" placeholder="验证码" name="verifycode" class="captcha"><br><br>
<img id="captcha_img" src="captcha.php?r=<?php echo rand();?>" alt="验证码">
<label><a href="javascript:void(0)" rel="external nofollow" onclick="document.getElementById('captcha_img').src='captcha.php?r='+Math.random()">换一个</a> </label>

captcha.php后面加上一个随机参数是为了实现换一个验证码的功能,,换一个功能通过简单的js即可实现。如果没有这个功能可以不用参数。

看完上述内容,你们对如何在php中使用GD库实现一个验证码功能有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI