Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:任何一门web语言, 会话控制都非常重要, 因为他是用户进入项目的第一道门
<?php session_start(); if (isset($_SESSION['user']) && $_SESSION['user']==='pipy'){ echo '用户:'.$_SESSION['user'].'已登录!<hr>'; echo '<a href="dispatch.php?action=logout">退出</a>'; }else{ echo '<a href="dispatch.php?action=login">请登录!</a>'; }
<?php session_start(); require __DIR__ . '/conn.php'; $action = isset($_GET['action']) ? $_GET['action'] : 'login'; $action = htmlentities(strtolower(trim($action))); switch ($action) { case 'login': include __DIR__ . '/login.php'; break; case 'check': include __DIR__ . '/check.php'; break; case 'logout': include __DIR__ . '/logout.php'; break; default: include __DIR__ . '/index.php'; }
<?php //数据库连接参数 $db=[ 'type'=>'mysql', 'host'=>'localhost', 'dbname'=>'pipysoft', 'username'=>'root', 'password'=>'123456', ]; //DSN $dsn="{$db['type']}:host={$db['host']};dbname={$db['dbname']}"; try { $pdo = new PDO($dsn, $db['username'], $db['password']); //print_r($pdo); }catch (PDOException $e){ die('Connection Failed: ' . $e->getMessage()); }
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { $user = $_POST['user']; $password = $_POST['password']; $sql = 'SELECT * FROM `users` WHERE `user` = :user AND `password` = :password LIMIT 1'; $stmt = $pdo->prepare($sql); $stmt->execute(['user'=>$user, 'password'=>$password]); $user = $stmt->fetch(PDO::FETCH_ASSOC); if (false === $user) { echo '<script>alert("用户名或密码错误或用户不存在!");history.back();</script>'; die; } $_SESSION['user'] = $user['user']; echo '<script>alert("登录成功");location.assign("index.php");</script>'; exit; } else { die('请求错误!'); }
<?php if (isset($_SESSION['user'])) { echo '<script>alert("您已经登录,请不要重复登录!");location.assign("index.php");</script>'; } ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>用户登录</title> </head> <body> <h3>用户登录</h3> <form action="dispatch.php?action=check" method="post" onsubmit="return isEmpty();"> <p> <label for="user">用户名:</label> <input type="text" name="user" id="user"> </p> <p> <label for="password">密码:</label> <input type="password" name="password" id="password"> </p> <p> <button>登录</button> </p> </form> <script> function isEmpty() { var user = document.getElementById('user').value; var password = document.getElementById('password').value; if (user.length=== 0 || password.length===0) { alert('用户名和密码不能为空'); return false; } } </script> </body> </html>
<?php if (isset($_SESSION['user'])) { session_destroy(); echo '<script>alert("退出登录成功!");location.assign("index.php");</script>'; } else { echo '<script>alert("请登录!");location.assign("login.php");</script>'; }