php中运用GD库实现简单验证码

时间:2023-03-08 20:33:14
php中运用GD库实现简单验证码

昨天学习了运用php的GD库进行验证码的实现。

首先可以用phpinfo()函数看一下GD库有没有安装,我用的wampserver是自动给安装的。

主要的步骤是:

1、生成验证码图片

2、随机生成字符,画到图片上,并把生成的字符追加到验证码字符串中

4、把验证码字符串保存到$_SESSION中

5、随机生成干扰元素

下面贴代码,注释比较详细:

 <?php
 session_start();
 $image_height = 30;
 $image_width = 100;
 $image = imagecreatetruecolor($image_width,$image_height);
 //验证码背景颜色
 $bgcolor = imagecolorallocate($image,255,245,255);
 //从左上角像验证码图片填充背景色
 imagefill($image,0,0,$bgcolor);
 //验证码字符串
 $captch_code ='';
 //生成字符
 for ($i = 0;$i<4;$i++){
 //  随机字符颜色
     $fontColor = imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120));
 //  字符数据库
     $data = 'abcdefghizklmnpqrstuvwxy0123456789';
 //  随机选取字符
     $fontContent = substr($data,rand(0,strlen($data))-1,1);
 //  追加到验证码字符串
     $captch_code.=$fontContent;
 //  随机生成字符位置
     $x = ($i*$image_width/4)+rand(0,$image_width/8);
     $y = rand(0,$image_height/2);
     //imagestring方法中默认字体为1-5
     $font = 5;
     imagestring($image,$font,$x,$y,$fontContent,$fontColor);
 }
 //用session储存验证码
 $_SESSION['authcode']=$captch_code;
 //画出干扰点
 for ($i=0;$i<200;$i++){
     $pointColor = imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200));
     imagesetpixel($image,rand(0,$image_width),rand(0,$image_height),$pointColor);
 }
 //画出干扰线
 for ($i=0;$i<3;$i++){
     $lineColor = imagecolorallocate($image,rand(80,220),rand(80,220),rand(80,220));
     imageline($image,rand(0,$image_width/2),rand(0,$image_height),rand($image_width/2,$image_width),rand(0,$image_height),$lineColor);
 }
 header('content-type:image/png');
 imagepng($image);
 imagedestroy($image);
 ?>

这样就实现了简单的验证码,当然还可对里边的字符进行扭曲的操作。

如果要实现中文的验证码在画字时要用到imagettftext($image, $size, $angle, $x, $y, $color, $fontfile, $text)这个函数,这里的$fontfile可以是支持中文的ttf字体的路径