如何使用 PHP 制作验证码?创建画布、生成验证码并添加文本到画布。添加干扰元素,发送 HTTP 标头并输出验证码图像。通过使用 PHP,您可以创建安全的验证码来保护您的网站免受恶意自动攻击。

如何使用 PHP 制作验证码
验证码是一种安全机制,用于防止恶意软件或机器人自动提交表单或执行其他未经授权的操作。以下是如何使用 PHP 制作验证码:
1. 创建画布
<code class="php"><?php $image = imagecreatetruecolor(120, 30); $background = imagecolorallocate($image, 255, 255, 255); imagefill($image, 0, 0, $background); ?></code>
2. 生成验证码
立即学习“PHP免费学习笔记(深入)”;
<code class="php">$chars = 'abcdefghijkmnpqrstuvwxyz23456789';
$text = '';
for ($i = 0; $i < 5; $i++) {
$text .= $chars[rand(0, strlen($chars) - 1)];
}
?></code>3. 添加文本到画布
<code class="php">$font = 'fonts/verdana.ttf'; $font_size = 20; $font_color = imagecolorallocate($image, 0, 0, 0); imagettftext($image, $font_size, 0, 10, 25, $font_color, $text); ?></code>
4. 添加干扰元素
<code class="php">for ($i = 0; $i < 50; $i++) {
$x1 = rand(0, 120);
$y1 = rand(0, 30);
$x2 = rand(0, 120);
$y2 = rand(0, 30);
imageline($image, $x1, $y1, $x2, $y2, $font_color);
}</code>5. 发送 HTTP 标头
<code class="php">header('Content-Type: image/png');
?></code>6. 输出验证码图像
<code class="php">imagepng($image); imagedestroy($image); ?></code>
用法:
<code class="php"><img src="captcha.php" alt="验证码" /></code>
通过使用 PHP,您可以创建安全且难以破解的验证码来保护您的网站免受恶意自动攻击。











