PHP验证码生成与测试
PHP验证码生成与测试
<?php
session_start();
require_once 'Captcha.php';$message = '';
$success = false;// 检查表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['captcha'])) {if (Captcha::validate($_POST['captcha'])) {$message = '验证码正确!';$success = true;} else {$message = '验证码错误,请重试!';}
}
?><!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>验证码测试</title><style>body {font-family: Arial, sans-serif;max-width: 500px;margin: 50px auto;padding: 20px;text-align: center;}.captcha-img {margin: 20px 0;border: 1px solid #ddd;cursor: pointer;height: 50px; /* 固定高度避免布局跳动 */}.message {padding: 10px;margin: 10px 0;border-radius: 4px;}.success {background-color: #dff0d8;color: #3c763d;}.error {background-color: #f2dede;color: #a94442;}</style>
</head>
<body><h1>验证码测试</h1><?php if ($message): ?><div class="message <?= $success ? 'success' : 'error' ?>"><?= htmlspecialchars($message) ?></div><?php endif; ?><form method="POST" action=""><div><!-- 只保留一个验证码图片元素 --><img id="captcha-image" class="captcha-img" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=" alt="验证码" title="点击刷新验证码"></div><div><input type="text" name="captcha" placeholder="请输入验证码" required></div><div><button type="submit">提交验证</button><button type="button" id="refresh-btn">刷新验证码</button></div></form><script>const captchaImage = document.getElementById('captcha-image');const refreshBtn = document.getElementById('refresh-btn');// 获取验证码Base64async function refreshCaptcha() {try {const timestamp = Date.now();const response = await fetch(`generate_captcha.php?t=${timestamp}`);const blob = await response.blob();return new Promise((resolve) => {const reader = new FileReader();reader.onload = () => {captchaImage.src = reader.result;};reader.readAsDataURL(blob);});} catch (error) {console.error('刷新验证码失败:', error);}}// 初始加载和点击刷新refreshCaptcha();captchaImage.addEventListener('click', refreshCaptcha);refreshBtn.addEventListener('click', refreshCaptcha);</script>
</body>
</html>
源码资源:https://download.csdn.net/download/weixin_43050480/91998494