With the rapid development of the internet, CAPTCHA has become a widely used security mechanism for websites and applications. While traditional CAPTCHAs usually use English characters and numbers, sometimes we need to generate CAPTCHAs with Chinese characters. This article will explain how to generate CAPTCHA images with Chinese characters using PHP, and it provides specific code examples.
<?php
$chineseChars = array('一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '百', '千', '万', '亿', '天', '地', '王', '赵', '钱', '孙');
?>
<?php
$code = ''; // Initialize CAPTCHA as an empty string
for ($i = 0; $i < 3; $i++) {
$index = mt_rand(0, count($chineseChars) - 1); // Randomly select a character
$code .= $chineseChars[$index]; // Append the character to the code
}
?>
<?php
$width = 120; // Canvas width
$height = 40; // Canvas height
// Create the canvas
$image = imagecreate($width, $height);
// Set the background color
$bgColor = imagecolorallocate($image, 255, 255, 255); // White background
// Randomly choose a color for the CAPTCHA text
$textColor = imagecolorallocate($image, mt_rand(0, 150), mt_rand(0, 150), mt_rand(0, 150));
// Path to the Chinese font
$fontFile = 'path/to/chinese_font.ttf';
// Draw the CAPTCHA text
imagettftext($image, 20, 0, 10, 30, $textColor, $fontFile, $code);
// Output the CAPTCHA image to the browser
header('Content-Type: image/png');
imagepng($image);
// Destroy the image resource
imagedestroy($image);
?>
<?php
session_start();
// Store the CAPTCHA in the session
$_SESSION['captcha'] = $code;
?>
You can then embed the CAPTCHA image in an HTML form for the user to enter the code:
<form action="verify.php" method="post">
<input type="text" name="code" placeholder="Please enter the CAPTCHA">
<button type="submit">Submit</button>
</form>