<?php
session_start();
// 生成随机验证码
$code = '';
$chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
for ($i = 0; $i < 4; $i++) {
    $code .= $chars[rand(0, strlen($chars) - 1)];
}
$_SESSION['authcode'] = $code;

// 创建验证码图片
$width = 120;
$height = 40;
$img = imagecreate($width, $height);

// 生成随机背景色
$bg_color = imagecolorallocate($img, rand(200, 255), rand(200, 255), rand(200, 255));

// 生成随机干扰点
for ($i = 0; $i < 100; $i++) {
    $point_color = imagecolorallocate($img, rand(100, 150), rand(100, 150), rand(100, 150));
    imagesetpixel($img, rand(0, $width), rand(0, $height), $point_color);
}

// 生成随机干扰线
for ($i = 0; $i < 5; $i++) {
    $line_color = imagecolorallocate($img, rand(100, 150), rand(100, 150), rand(100, 150));
    imageline($img, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $line_color);
}

// 生成随机文字颜色
$text_color = imagecolorallocate($img, rand(0, 100), rand(0, 100), rand(0, 100));

// 绘制验证码文字
try {
    // 尝试使用TrueType字体
    for ($i = 0; $i < 4; $i++) {
        $font_size = rand(14, 18);
        $angle = rand(-15, 15);
        $x = 10 + $i * 25;
        $y = rand(25, 30);
        imagettftext($img, $font_size, $angle, $x, $y, $text_color, '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', $code[$i]);
    }
} catch (Exception $e) {
    // 回退到默认字体
    imagestring($img, 5, 20, 10, $code, $text_color);
}

header('Content-Type: image/png');
imagepng($img);
imagedestroy($img);
?>
