PHP实现简单汉字验证码

yipeiwu_com6年前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进行验证了。

以上所述就是本文的全部内容了,希望大家能够喜欢。

相关文章

phpmyadmin里面导入sql语句格式的大量数据的方法

sql.php文件的内容如下: 复制代码 代码如下:<? system("mysql -uroot -pmypassword database < a.sql"); prin...

php实现有序数组打印或排序的方法【附Python、C及Go语言实现代码】

本文实例讲述了php实现有序数组打印或排序的方法。分享给大家供大家参考,具体如下: 有序的数组打印或排序对于php来讲非常的简单了这里整理了几个不同语言的做法的实现代码,具体的我们一起来...

php通过baihui网API实现读取word文档并展示

项目中遇到一个小问题,想实现php 如何读取word文档,并将其内容原样显示 可以 使用API 可以看看baihui.com 的写写应用 的API 申请一个 APPKEY 就能使用,你可...

php Undefined index和Undefined variable的解决方法

$act=$_POST['act']; 用以上代码总是提示 Notice: Undefined index: act in F:\win...

PHP url 加密解密函数代码

复制代码 代码如下: $returnUrl = rawurlencode(base64_encode($returnUrl)); //编码 $returnUrl = parse_str(...