php验证码实现及使用--面向过程版

来源:互联网 发布:拼接屏调试软件 编辑:程序博客网 时间:2024/05/01 04:36

又迎来了七夕!昨晚实现了这个程序的基本功能,今天中午完善了一下。唯一遗憾的是闹钟没有叫醒我,所以,没有看到流星雨!那么就用这个代码来作为补偿吧!微笑第一次写技术博客,一来可以供以后复习,而来在理一下自己的思路。看到的哥们还请不吝赐教啊!^_^

 

验证码的特点:

1)可以随机显示字符

2)按照自己喜欢的方式确定显示的验证码类型(0-只显示数字,1-显示小写字母和数字,2-显示数字、大小写字母)

3)可以设置自己要求的显示大小

4)可以添加干扰线和干扰点

 

实现步骤

第一步:实现随机生成一个指定字符个数的验证码函数getCode()

 /**  * 功能:随机生成一个验证码函数  * @param $code_len 验证码显示的字符个数  * @param $type 验证码类型(默认 0-全为数字, 1-小写字母和数字,2-小写、大写、数字组成)  * @author MaChaoHui<Mchgloak11520@gmail.com>  * */   function getCode( $code_len, $type = 2 ){   $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';   $type_pos = array( 9, 35, strlen($str)-1 ); //类型位置定界    //随机产生验证码内容  $content = '';  for( $i=0; $i<$code_len; $i++ ){   $content .= $str[rand(0, $type_pos[$type])];  }    return $content; }

 

此时在浏览器中的效果为:

第二步:绘制验证码背景。

我们知道PHP的GD库绘图有几个步骤:1)绘制一个画布、分配背景颜色;2)绘图;3)输出图像;4)销毁画布(释放内存)。所以接下来就是按照这几个步骤来绘制验证码。

1)绘制画布、分配背景颜色(imagecreatetruecolor( $width, $height );函数)

$width = $code_len * 20;  $height = 30;  $im = imagecreatetruecolor( $width, $height ); $bg = imagecolorallocate( $im, 200, 200, 200 ); //2)绘制背景  imagefill( $im, 0, 0, $bg ); //3). 输出图像  header("Content-Type:image/png");  //设置响应头信息  imagepng( $im );          //4). 销毁画布(释放内存)  imagedestroy( $im ); 


 

 

此时实现的效果为:

第三步:绘制验证码字体。

核心代码:

//绘制验证码内容(一个个字符绘制)  for( $i=0; $i<$code_len; $i++ ){   imagettftext($im, 18, rand(-40, 40), 6+(18*$i), 24, $color[rand(0, 4)], 'ariblk.ttf', $str[$i]);  }

 

此时效果为:

可见,没有干扰线和干扰点也没有边框,不是很好看。所以接下来添加这几个。

 

第四步:添加干扰线、干扰点和边框。

核心代码:

//绘制边框  imagerectangle($im, 0, 0, $width-1, $height-1, $color[rand(0, 4)]);  //随机添加干扰点  for( $i=0; $i<200; $i++ ){   $col = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255));   imagesetpixel($im, rand(0, $width), rand(0, $height), $col);  }  //随机添加干扰线  for( $i=0; $i<5; $i++ ){   $col = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255));//绘制随机颜色   imageline($im, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $col);  }


 

 

 

使用:

<form name="myForm" method="post" action="#">  <label>用户名:</label><input type="text" name="username"/><br /> <label>密  码:</label><input type="password" name="passwd" /><br /> <label>验证码:</label><input type="text" name="code" /> <img src="VerifyCode.php" onclick="this.src = 'VerifyCode.php?id='+Math.random()" /><br /> <input type="submit" value="提交" /> </form>

 

 

此时效果:

 

 

 

原创粉丝点击