php怎么构造一个验证码,PHP封装一个生成验证码的函数

整体的思路:

1、准备画布

2、生成颜色

3、生成的字符范围

4、开始写字

5、插入干扰线(点)

6、指定输出的类型

7、准备输出图片

8、销毁

// 生成随机验证码的方法

function verify($width = 100, $height = 40, $num = 5, $type = 3)

{

// 1、准备画布

$image = imagecreatetruecolor($width, $height);

imagefilledrectangle($image, 0, 0, $width, $height, lightColor($image)); //给画布填充一个浅色背景

// 2、生成颜色

// 3、需要什么字符

$string = '';

switch ($type) {

case 1: //0-9的数字

$str = '0123456789';

//str_shuffle($str); 随机打乱$str

$string = substr(str_shuffle($str), 0, $num);

break;

case 2: //a-b的字母

$arr = range('a', 'z');

shuffle($arr);

$tmp = array_slice($arr, 0, $num);

$string = join('', $tmp);

break;

case 3: //0-9 a-z A-Z的随机组合

$str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

$string = substr(str_shuffle($str), 0, $num);

break;

}

// 4、开始写字

for ($i = 0; $i < $num; $i++) {

$x = floor($width / $num) * $i;

$y = mt_rand(10, $height - 20);

imagechar($image, 5, $x, $y, $string[$i], deepColor($image));

}

// 5、插入干扰线(点)

for ($i = 0; $i < 5; $i++) {

imagearc($image, mt_rand(10, $width), mt_rand(10, $height), mt_rand(10, $width), mt_rand(10, $height), mt_rand(0, 10), mt_rand(0, 270), deepColor($image));

}

for ($i = 0; $i < 50; $i++) {

imagesetpixel($image, mt_rand(0, $width), mt_rand(10, $height), deepColor($image));

}

// 6、指定输出的类型

header('Content-type:image/png');

// 7、准备输出图片

imagepng($image);

// 8、销毁

imagedestroy($image);

return $string;

}

// 生成浅的颜色

function lightColor($image)

{

return imagecolorallocate($image, mt_rand(130, 255), mt_rand(130, 255), mt_rand(130, 255));

}

// 生成深色

function deepColor($image)

{

return imagecolorallocate($image, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));

}

verify();

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值