php实现验证码注册
PHP 验证码注册实现
生成验证码图片
创建 captcha.php 文件生成验证码图片:
session_start();
$code = rand(1000, 9999);
$_SESSION['captcha'] = $code;
$image = imagecreatetruecolor(100, 30);
$bgColor = imagecolorallocate($image, 255, 255, 255);
$textColor = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, 100, 30, $bgColor);
imagestring($image, 5, 25, 8, $code, $textColor);
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
注册表单HTML
创建包含验证码的表单页面 register.html:
<form action="register.php" method="post">
<label>用户名: <input type="text" name="username"></label>
<label>密码: <input type="password" name="password"></label>
<label>验证码: <input type="text" name="captcha"></label>
<img src="captcha.php" onclick="this.src='captcha.php?'+Math.random()">
<button type="submit">注册</button>
</form>
验证处理
创建 register.php 处理注册逻辑:

session_start();
if ($_POST['captcha'] != $_SESSION['captcha']) {
die('验证码错误');
}
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
// 存储用户数据到数据库
// $pdo->prepare("INSERT INTO users (username, password) VALUES (?, ?)")->execute([$username, $password]);
echo '注册成功';
安全增强措施
验证码图片添加干扰元素:
// 在captcha.php中添加
for ($i = 0; $i < 5; $i++) {
$color = imagecolorallocate($image, rand(0,255), rand(0,255), rand(0,255));
imageline($image, rand(0,100), rand(0,30), rand(0,100), rand(0,30), $color);
}
设置验证码有效期:

// 在captcha.php中
$_SESSION['captcha_time'] = time();
// 在register.php中验证
if (time() - $_SESSION['captcha_time'] > 300) {
die('验证码已过期');
}
数据库存储
完整的用户注册存储示例:
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
$stmt->execute([$username, $password]);
验证码刷新机制
JavaScript实现点击刷新:
document.querySelector('img').addEventListener('click', function() {
this.src = 'captcha.php?' + new Date().getTime();
});






