<!-- HTML 页面 -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="login">
<h1>登录</h1>
<?php
// 获取表单提交的数据
$username = $_POST['username'];
$password = $_POST['password'];
// 如果表单已提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// 验证用户输入
if ($username == 'admin' && $password == 'admin123') {
// 登录成功,跳转到欢迎页面
header('Location: welcome.php');
exit();
} else {
// 登录失败,显示错误提示
echo '<p class="error">用户名或密码不正确</p>';
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<input type="text" name="username" placeholder="用户名" required>
<input type="password" name="password" placeholder="密码" required>
<button type="submit">登录</button>
</form>
</div>
</body>
</html>
上述代码使用了 HTML 和 PHP 混合编程的方式,通过 HTML 表单提交用户输入的用户名和密码,PHP 代码接收并验证数据,如果登录成功则跳转到欢迎页面,否则显示错误提示。以下是代码的注释:
<!-- HTML 页面 -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
<link rel="stylesheet" href="styles.css"> <!-- 引入 CSS 样式表 -->
</head>
<body>
<div class="login"> <!-- 开始登录界面的 DIV 容器 -->
<h1>登录</h1> <!-- 显示登录标题 -->
<?php
// 获取表单提交的数据
$username = $_POST['username'];
$password = $_POST['password'];
// 如果表单已提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// 验证用户输入
if ($username == 'admin' && $password == 'admin123') {
// 登录成功,跳转到欢迎页面
header('Location: welcome.php');
exit(); // 退出程序
} else {
// 登录失败,显示错误提示
echo '<p class="error">用户名或密码不正确</p>';
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<!-- 显示登录表单 -->
<input type="text" name="username" placeholder="用户名" required>
<input type="password" name="password" placeholder="密码" required>
<button type="submit">登录</button>
</form>
</div> <!-- 结束登录界面的 DIV 容器 -->
</body>
</html>
此外,我们还可以添加 CSS 样式表来美化登录页面。例如,以下是一个简单的 CSS 样式表,可为登录界面添加一些基本样式:
.login {
width: 400px;
margin: 50px auto;
text-align: center;
padding: 20px;
border-radius: 10px;
box-shadow: 0px 0px 10px #666;
background-color: #fff;
}
h1 {
margin-top: 0;
color: #333;
font-weight: normal;
}
input[type="text"],
input[type="password"],
button {
width: 100%;
padding: 10px;
margin-bottom: 20px;
border-radius: 5px;
border: none;
}
input[type="text"]:focus,
input[type="password"]:focus {
outline: none;
box-shadow: 0px 0px 5px #ccc;
}
button[type="submit"] {
background-color: #39f;
color: #fff;
cursor: pointer;
transition: background-color 0.2s ease;
}
button[type="submit"]:hover {
background-color: #66a6e1;
}
.error {
color: #f00;
}
最终,经过以上步骤,我们可以获得一个简单美观的登录界面。