700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > php怎么构造一个验证码 PHP封装一个生成验证码的函数

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

时间:2023-06-09 19:36:59

相关推荐

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();

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。