利用php生成验证码

yipeiwu_com5年前PHP代码库

话不多说,请看代码:

<?php 
/**
 * php生成验证码
 * @param $width 画布宽
 * @param $height 画布高
 * @param $vcodelen 验证码长度
 * @param $pointnum 干扰像素点数量
 * @param $linenum 干扰线条数量
 *
 * 思路:创建验证码画布,生成并填充背景色,生成验证码内容/干扰像素点/线,填充到画布,输出。
 */
 $width = 100;
 $height = 30;
 $vcodelen = 4;
 $pointnum = 200;
 $linenum = 3;
 // 创建画布
 $image = imagecreatetruecolor($width, $height);
 // 创建色块
 $bgcolor = imagecolorallocate($image, 255, 255, 255);
 // 填充画布背景色
 imagefill($image, 0, 0, $bgcolor);
 // 验证码内容
 for ($i=0; $i < $vcodelen; $i++) { 
  // 字体大小
  $fontsize = 5;
  // 字体颜色,颜色在限定范围内随机
  $fontcolor = imagecolorallocate($image, rand(0,120), rand(0,120), rand(0,120));
  $data = 'abcdefghijklmnopqrstuvwxyz0123456789';
  // 验证码内容在以上字符串内随机截取
  $fontcontent = substr($data, rand(0,strlen($data)),1);
  // 字符串显示位置
  $x = ($i*$width/4)+rand(5,15);
  $y = rand(5,10);
  // 字符串填充图片
  // imagestring的字体大小可选1-5,字体再大需要用imagettftext函数(需要字体文件)
  imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);
  // imagettftext($image, $fontsize, 0, $x, $y, $fontcolor, '/font/Geneva.dfont', $fontcontent);
 }
 // 干扰像素点
 for ($i=0; $i < $pointnum; $i++) { 
  $pointcolor = imagecolorallocate($image, rand(0,120), rand(0,120), rand(0,120));
  // 画布填充像素点函数
  imagesetpixel($image, rand(0,$width), rand(0,$height), $pointcolor);
 }
 // 干扰线条
 for ($i=0; $i < $linenum; $i++) { 
  $linecolor = imagecolorallocate($image, rand(0,120), rand(0,120), rand(0,120));
  // 画布填充线条函数
  imageline($image, rand(0,$width), rand(0,$height), rand(0,$width), rand(0,$height), $linecolor);
 }
 // 图片输出格式
 header('content-type: image/png');
 // 输出验证码图片
 imagepng($image);
 // 销毁画布
 imagedestroy($image);
?>

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持【宜配屋www.yipeiwu.com】!

相关文章

php实现基于PDO的预处理示例

本文实例讲述了php实现基于PDO的预处理。分享给大家供大家参考,具体如下: $servername="localhost"; $username="root"; $password...

简单谈谈 php 文件锁

锁机制之所以存在是因为并发导致的资源竞争,为了确保操作的有效性和完整性,可以通过锁机制将并发状态转换成串行状态。作为锁机制中的一种,PHP的文件锁也是为了应对资源竞争。假设一个应用场景,...

将二维数组转为一维数组的2种方法

如何将下面的二维数组转为一维数组。 复制代码 代码如下:$msg = array(  array(    'id'=>'45',    'name'=>'jack'  ), ...

PHP生成plist数据的方法

本文实例讲述了PHP生成plist数据的方法。分享给大家供大家参考。具体如下: 这段代码实现PHP数组转换为苹果plist XML或文本格式 <?PHP /** *...

php 网页播放器用来播放在线视频的代码(自动判断并选择视频文件类型)

在web开发中经常会碰到一些简单的视频播放功能,但现在的视频格式不同,并且可以动态增加,所以我们就必须把视频保存到数据哦,好了下面我们来看我写的段简单的 php视频网页播放器代码吧。 复...