利用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 删除一维数组中某一个值元素的操作方法

1. 自己写for循环 从array里去掉$tmp这个元素的值 <?php $tmp = '324'; $arr = array( '0' => '321', '...

php set_time_limit(0) 设置程序执行时间的函数

set_time_limit(0); 括号里边的数字是执行时间,如果为零说明永久执行直到程序结束,如果为大于零的数字,则不管程序是否执行完成,到了设定的秒数,程序结束。 一个简单的例子,...

谈谈新手如何学习PHP网络编程第1/2页

文章开头就列举了那么多联系方式,难免会让大家感觉有点AD的意味,但是不容质疑的是,默默的确有那么丁点的表现欲^_^,虽然有时候过于细致会被人说婆妈,但是幸好这种细致对于编程来说,还是蛮有...

PHP中CURL的CURLOPT_POSTFIELDS参数使用细节

在通常情况下,我们使用 CURL 来提交 POST 数据的时候,我们已经习惯了这样的写法:复制代码 代码如下:curl_setopt( $ch, CURLOPT_POSTFIELDS,$...

PHP框架Laravel的小技巧两则

用 Laravel 作为 PHP 开发框架很久了,但是有些官方文档中没有覆盖到的地方,每隔一段时间又会忘记。最近做了一点简单的整理,顺便记录下来备忘。 1. Route::control...