How can PHP generate random verification codes with color?

You can use the following code to generate a random verification code and set the color:

<?php
// 生成随机验证码
$random_code = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 6);

// 创建一张空白画布
$image = imagecreatetruecolor(100, 50);

// 设置背景颜色
$bg_color = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bg_color);

// 设置验证码文本颜色
$text_color = imagecolorallocate($image, 0, 0, 0);

// 将验证码文本写入画布
imagettftext($image, 20, 0, 10, 30, $text_color, 'arial.ttf', $random_code);

// 设置响应的内容类型
header('Content-type: image/png');

// 输出图像
imagepng($image);

// 释放内存
imagedestroy($image);
?>

Please make sure the font file arial.ttf is available on the server for generating captcha text. You can also adjust parameters such as the background color, captcha text color, and captcha text size as needed.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds