验证码(CAPTCHA)是一种用于区分人类和计算机的程序,通常用于网站的安全验证。它通过要求用户识别并输入图像中的文字或数字来防止自动化程序(如机器人)的恶意行为。
以下是一个简单的PHP图像验证码示例:
<?php
session_start();
// 生成随机字符串
function generateRandomString($length = 6) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
// 创建验证码图像
function createCaptchaImage($code) {
$width = 150;
$height = 50;
$image = imagecreatetruecolor($width, $height);
$backgroundColor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $backgroundColor);
// 添加干扰线
for ($i = 0; $i < 5; $i++) {
$color = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $color);
}
// 添加验证码文字
$textColor = imagecolorallocate($image, 0, 0, 0);
imagettftext($image, 20, 0, 30, 30, $textColor, 'arial.ttf', $code);
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
}
// 生成验证码并保存到session
$code = generateRandomString();
$_SESSION['captcha'] = $code;
createCaptchaImage($code);
?>
希望这个回答能帮助你理解PHP编写验证码的基础概念和相关实现。
领取专属 10元无门槛券
手把手带您无忧上云