|
发表于 2023-5-6 16:57:55
|
显示全部楼层
本楼为最佳答案
 根据您的需求,我提供了一个简单的登录验证的例子。这里我们会用到两个 PHP 文件: login.php 和 welcome.php 。
首先是 login.php ,它包含了登录表单的 HTML 代码以及处理登录验证的 PHP 代码:
- <?php
- session_start();
- if (isset($_POST['submit'])) {
- $password = $_POST['password'];
- $correct_password = 'your_password_here'; // 设置正确的密码
- if ($password == $correct_password) {
- $_SESSION['user'] = 'username'; // 登录成功后,将用户信息存储到 session 中
- header('Location: welcome.php'); // 跳转到 welcome.php 页面
- exit;
- } else {
- $error_message = "密码错误,请重新输入!";
- }
- }
- ?>
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>一个最简单的表单</title>
- </head>
- <body>
- <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
- <label>密码:<input type="password" name="password"></label><br><br>
- <button type="submit" name="submit">提交</button>
- </form>
- <?php
- if (isset($error_message)) {
- echo "<p style='color:red;'>$error_message</p>";
- }
- ?>
- </body>
- </html>
复制代码
接下来是 welcome.php ,在这个页面中我们将检查用户是否已经登录:
- <?php
- session_start();
- if (!isset($_SESSION['user'])) {
- header('Location: login.php');
- exit;
- }
- ?>
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>欢迎页面</title>
- </head>
- <body>
- <h1>欢迎,您已成功登录!</h1>
- <p><a href="logout.php">退出登录</a></p>
- </body>
- </html>
复制代码
最后,我们创建一个 logout.php 文件以处理用户的退出登录操作:
- <?php
- session_start();
- session_destroy();
- header('Location: login.php');
- exit;
- ?>
复制代码
将这些文件放到您的 web 服务器上,并设置正确的密码。现在,您的用户可以通过输入正确的密码登录并访问 welcome.php 页面。如果密码错误,将显示错误消息。 |
|