php验证码怎么实现
生成随机验证码字符串
在PHP中生成验证码通常需要创建一个随机字符串,包含数字、字母或其组合。以下是一个生成4位随机数字验证码的示例:
$length = 4;
$code = substr(str_shuffle("0123456789"), 0, $length);
如果需要包含字母,可以修改为:
$chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$code = substr(str_shuffle($chars), 0, $length);
创建验证码图片
使用GD库将验证码字符串渲染为图片:
header('Content-Type: image/png');
$image = imagecreatetruecolor(200, 50);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image, 0, 0, 200, 50, $bgColor);
$textColor = imagecolorallocate($image, 0, 0, 0);
imagettftext($image, 20, 0, 50, 35, $textColor, 'path/to/font.ttf', $code);
imagepng($image);
imagedestroy($image);
添加干扰元素
为提高安全性,可以添加干扰线和噪点:
// 添加干扰线
for ($i = 0; $i < 5; $i++) {
$lineColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
imageline($image, rand(0, 200), rand(0, 50), rand(0, 200), rand(0, 50), $lineColor);
}
// 添加噪点
for ($i = 0; $i < 100; $i++) {
$pixelColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
imagesetpixel($image, rand(0, 200), rand(0, 50), $pixelColor);
}
存储验证码到Session
将生成的验证码存入Session以便后续验证:
session_start();
$_SESSION['captcha'] = $code;
验证用户输入
在表单提交处理页面验证用户输入:
session_start();
if (strtolower($_POST['captcha']) !== strtolower($_SESSION['captcha'])) {
die('验证码错误');
}
unset($_SESSION['captcha']);
完整示例代码
将以上步骤整合为一个完整的验证码生成和验证流程:
// captcha.php
session_start();
$length = 6;
$chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$code = substr(str_shuffle($chars), 0, $length);
$_SESSION['captcha'] = $code;
header('Content-Type: image/png');
$image = imagecreatetruecolor(200, 50);
$bgColor = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image, 0, 0, 200, 50, $bgColor);
$textColor = imagecolorallocate($image, 0, 0, 0);
imagettftext($image, 20, 0, 50, 35, $textColor, 'arial.ttf', $code);
// 干扰线和噪点
for ($i = 0; $i < 5; $i++) {
imageline($image, rand(0, 200), rand(0, 50), rand(0, 200), rand(0, 50),
imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255)));
}
for ($i = 0; $i < 100; $i++) {
imagesetpixel($image, rand(0, 200), rand(0, 50),
imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255)));
}
imagepng($image);
imagedestroy($image);
在HTML表单中引用:
<img src="captcha.php" onclick="this.src='captcha.php?'+Math.random()">
<input type="text" name="captcha" required>
验证页面:
session_start();
if (empty($_SESSION['captcha']) || strtolower($_POST['captcha']) !== strtolower($_SESSION['captcha'])) {
die('验证码错误');
}
unset($_SESSION['captcha']);
// 继续处理表单






