利用php写一个验证码功能

利用php写一个验证码功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
// 设置图片宽度和高度
$width = 100;
$height = 30;

// 创建一个空白的图片
$image = imagecreate($width, $height);

// 设置背景颜色为白色
imagecolorallocate($image, 255, 255, 255);

// 定义字符集
$str = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";

// 获取字符集的长度
$strlen = strlen($str) - 1;

// 设置字体文件路径
$fileName = realpath("./yzm.ttf");

// 设置字体大小
$fontSize = 16;

// 循环生成四个字符
for ($i = 0; $i < 4; $i++) {
// 随机生成旋转角度
$angle = mt_rand(-30, 30);

// 随机生成字体颜色
$fontColor = imagecolorallocate($image, mt_rand(100, 180), mt_rand(100, 180), mt_rand(100, 180));

// 从字符集中随机选择一个字符
$text = $str[mt_rand(0, $strlen)];

// 在图片上绘制字符
imagettftext($image, $fontSize, $angle, 20 + ($i * 15), 20, $fontColor, $fileName, $text);
}

// 添加干扰线
for ($i = 0; $i < 5; $i++) {
// 随机生成线条颜色
$lineColor = imagecolorallocate($image, mt_rand(100, 180), mt_rand(100, 180), mt_rand(100, 180));

// 随机生成线条的起点坐标
$startX = mt_rand(0, $width);
$startY = mt_rand(0, $height);

// 随机生成线条的终点坐标
$endX = mt_rand(0, $width);
$endY = mt_rand(0, $height);

// 在图片上绘制线条
imageline($image, $startX, $startY, $endX, $endY, $lineColor);
}

// 设置响应头,指定输出的内容类型为PNG图片
header("Content-type: image/png");

// 输出图片
imagepng($image);
?>


利用php写一个验证码功能
https://hubiaonb.github.io/2024/04/17/phpyzm-jc/
作者
Master
发布于
2024年4月17日
许可协议