温馨提示×

温馨提示×

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

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

使用PHP怎么实现一个汉字验证码功能

发布时间:2020-12-23 16:44:02 来源:亿速云 阅读:103 作者:Leah 栏目:开发技术

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

创建背景画布

$image = imagecreatetruecolor(200, 60);
$background = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $background);

画干扰点

for ($i=0; $i < 300; $i++) { 
  $pixColor = imagecolorallocate($image, rand(150, 240), rand(150, 240), rand(150, 240));
  $pixX = rand(10, 190);
  $pixY = rand(5, 55);
  imagesetpixel($image, $pixX, $pixY, $pixColor);
}

画干扰线

//4条水平线
for ($i=0; $i < 5; $i++) { 
  $lineColor = imagecolorallocate($image, rand(50, 150), rand(50, 150), rand(50, 150));
  $lineX1 = 0;
  $lineX2 = 300;
  $lineY1 = ($i + 1) * 12;
  $lineY2 = ($i + 1) * 12;
  imageline($image, $lineX1, $lineY1, $lineX2, $lineY2, $lineColor);
}

//10条垂直线
for ($i=0; $i < 30; $i++) { 
  $lineColor = imagecolorallocate($image, rand(50, 150), rand(50, 150), rand(50, 150));
  $lineX1 = ($i + 1) * 10;
  $lineX2 = ($i + 1) * 10;
  $lineY1 = 0;
  $lineY2 = 60;
  imageline($image, $lineX1, $lineY1, $lineX2, $lineY2, $lineColor);
}

画汉字

$text = array('栀', '子', '花', '开');
for ($i=0; $i < 4; $i++) {
  $textColor = imagecolorallocate($image, rand(20, 100), rand(20, 100), rand(20, 100));
  $textX = $i * 50 + 10;
  $textY = rand(40, 60);
  imagettftext($image, 30, rand(20, 50), $textX, $textY, $textColor, "/Library/Fonts/华文仿宋.ttf", $text[$i]);
}

这里注意一下,字体文件一定要支持中文的

编码要使用utf-8,gbk的中文记得要转吗【iconv函数可以帮助你】

输出图像

header("Content-Type:image/png");
imagepng($image);

销毁资源

imagedestroy($image);

经过粗略的搞吧搞吧,中文验证码也就显示出来了,当然一般网站使用的时候会有一个汉字库种子,从里面随机取出特定个数的汉字显示,最后就是记录到session进行验证了。

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

向AI问一下细节

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

AI