PHP验证码模拟登录并保持登录涉及以下几个基础概念:
以下是一个简单的PHP验证码模拟登录并保持登录的示例代码:
<?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, 20, 5, $code, $textColor);
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?><?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
$captcha = $_POST['captcha'];
if (empty($username) || empty($password) || empty($captcha)) {
echo "所有字段都必须填写";
exit;
}
if (strtoupper($captcha) != strtoupper($_SESSION['captcha'])) {
echo "验证码错误";
exit;
}
// 假设用户名和密码验证通过
if ($username == 'admin' && $password == '123456') {
// 设置会话
$_SESSION['username'] = $username;
header('Location: dashboard.php');
exit;
} else {
echo "用户名或密码错误";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>登录</title>
</head>
<body>
<form method="post">
用户名: <input type="text" name="username"><br>
密码: <input type="password" name="password"><br>
验证码: <input type="text" name="captcha">
<img src="captcha.php" alt="验证码"><br>
<input type="submit" value="登录">
</form>
</body>
</html><?php
session_start();
if (isset($_SESSION['username'])) {
echo "欢迎回来," . $_SESSION['username'] . "!";
} else {
header('Location: login.php');
exit;
}
?>captcha.php文件路径正确。session_start()在每个页面的最开始调用。通过以上步骤,你可以实现一个基本的PHP验证码模拟登录并保持登录的功能。
没有搜到相关的沙龙