php结合GD库简单实现验证码的示例代码

2021-01-08 0 426

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

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

首先需要看php.ini配置文件中有没有GD库,如果没有开启,请自行开启下,我用的小皮面板,基本现在都给你带上了。

php结合GD库简单实现验证码的示例代码

需要生成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;

php结合GD库简单实现验证码的示例代码

3. 开启GD库画图

注意一下这个imagecolorallocate函数

php结合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结合GD库简单实现验证码的示例代码

前台的展示

<?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库验证码内容请搜索自学编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持自学编程网!

遇见资源网 PHP php结合GD库简单实现验证码的示例代码 http://www.ox520.com/22729.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务