请用php和html写登陆系统
以下是一个简单的登陆系统的例子,使用PHP和HTML编写:
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<style>
.container {
width: 300px;
margin: 0 auto;
padding-top: 100px;
}
.container input {
margin-bottom: 10px;
}
.container input[type="submit"] {
width: 100%;
}
</style>
</head>
<body>
<div class="container">
<h2>Login</h2>
<form action="login.php" method="POST">
<input type="text" name="username" placeholder="Username" required><br>
<input type="password" name="password" placeholder="Password" required><br>
<input type="submit" value="Login">
</form>
</div>
</body>
</html>
login.php:
<?php
session_start();
// 检查用户名和密码是否正确
function validate_login($username, $password) {
// 这里可以根据实际情况,从数据库或其他存储中验证用户名和密码
// 这里只是一个简单的例子,使用硬编码的用户名和密码
$valid_username = 'admin';
$valid_password = 'admin123';
if ($username == $valid_username && $password == $valid_password) {
return true;
}
return false;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
if (validate_login($username, $password)) {
// 登陆成功,将用户名保存到session中
$_SESSION['username'] = $username;
header("Location: welcome.php"); // 重定向到欢迎页面
exit();
} else {
echo "Invalid username or password";
}
}
?>
welcome.php:
<?php
session_start();
// 检查用户是否已经登陆
if (!isset($_SESSION['username'])) {
header("Location: index.html"); // 如果未登陆,重定向到登陆页面
exit();
}
$username = $_SESSION['username'];
?>
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h2>Welcome, <?php echo $username; ?></h2>
<a href="logout.php">Logout</a>
</body>
</html>
logout.php:
<?php
session_start();
session_destroy(); // 销毁session
header("Location: index.html"); // 重定向到登陆页面
exit();
?>
请确保在服务器上运行以上代码。当用户输入正确的用户名和密码后,将重定向到欢迎页面,并显示欢迎用户的消息。用户可以通过点击“Logout”链接注销并返回到登陆页面
原文地址: https://www.cveoy.top/t/topic/iSZG 著作权归作者所有。请勿转载和采集!