How can PHP generate a random verification code with co…

You can create a random verification code using the imagestring() function and add color to the code using the imagecolorallocate() function.

Here is an example code:

<?php
// 生成随机验证码
$code = generateRandomCode(6);

// 创建一个宽度为 100px、高度为 30px 的图像
$image = imagecreate(100, 30);

// 为图像分配背景颜色
$backgroundColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $backgroundColor);

// 为验证码添加文字颜色
$textColor = imagecolorallocate($image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));

// 将验证码绘制到图像上
imagestring($image, 5, 10, 8, $code, $textColor);

// 设置图像的 MIME 类型为 image/png
header('Content-type: image/png');

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

// 销毁图像资源
imagedestroy($image);

// 生成指定长度的随机验证码
function generateRandomCode($length) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $code = '';
    for ($i = 0; $i < $length; $i++) {
        $code .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $code;
}
?>

This code will generate an image with a width of 100 pixels and a height of 30 pixels, with a white background and randomly generated text color for the captcha. The image will then be output in PNG format.

bannerAds