基础篇——Session状态维持

基础篇——Session状态维持

在用户首次访问服务器时,服务器会创建一个Session并保存在服务器端,用于记录用户的状态信息;同时将Session ID通过Cookie发送给客户端,用于实现用户的身份认证。

当然这种做法会引起两个问题,其一是服务器端需要存储海量的Session,其二是由于Session ID保存在客户端,因此安全性相对较低。Token的出现完美地解决了这两个问题,通过将状态信息存储至客户端,减轻了服务器端的存储压力;通过对状态信息进行签名和验签,实现了用户的安全身份认证。

php中使用Session主要通过以下方式:

session_start(); 开启Session

$_SESSION['username'] = 'admin'; 设置Session变量

$username = $_SESSION['username']; 访问Session变量

session_unset(); session_destroy(); 清空并销毁Session

登录+注册+个人中心完整代码如下:

login.php:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Login</title>
    <link rel="stylesheet" href="login.css">
    <?php
		function filter($input) {
			$input = trim($input);
			$input = stripslashes($input);
			$input = htmlspecialchars($input);
			return $input;
		}
        session_start();
        if (!empty($_SESSION["username"])) echo "<script>window.location.href='center.php';</script>";
        $conn = mysqli_connect("localhost", "root", "root") or die("Failed to connect to MySQL!");
        $seldb = mysqli_select_db($conn, "users") or die("Failed to connect to the database!");
        mysqli_query($conn, "set names 'utf8'");
        $username_err = "";
        $password_err = "";
        if (isset($_POST["submit"])) {
            $username = filter($_POST["username"]);
            $password = filter($_POST["password"]);
            if (empty($username)) $username_err = "Username cannot be empty!";
            if (empty($password)) $password_err = "Password cannot be empty!";
            if ($username_err == "" && $password_err == "") {
                $search_query = "select * from password where username = '$username';";
                $search_result = mysqli_query($conn, $search_query);
                $search_result_array = mysqli_fetch_array($search_result);
                if (!empty($search_result) && $search_result_array['password'] == $password) {
                    $_SESSION["username"] = $username;
                    echo "<script>alert('Login Success!');window.location.href='center.php';</script>";
                }
                else echo "<script>alert('Failed to login!');</script>";
            }
        }
    ?>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>LOGIN PAGE</h1>
    </div>
    <div class="content">
        <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="POST">
            <table>
                <tr>
                    <td><label for="username">Username</label></td>
                    <td><input type="text" id="username" name="username"></td>
                    <td><span style="color: red; font-size: 12px;"><?php echo $username_err;?></span></td>
                </tr>
                <tr>
                    <td><label for="password">Password</label></td>
                    <td><input type="password" id="password" name="password"></td>
                    <td><span style="color: red; font-size: 12px;"><?php echo $password_err;?></span></td>
                </tr>
                <tr>
                    <td colspan="3" class="center-align">
                        <input type="submit" id="submit" name="submit" value="Submit">
                    </td>
                </tr>
                <tr>
                    <td colspan="3" class="center-align">
                        No account? <a href="register.php" id="link">Register</a>
                    </td>
                </tr>
            </table>
        </form>
    </div>
</div>
</body>
</html>

login.css:

.container{
	text-align: center;
	margin-top: 200px;
}
table{
    margin: 0 auto;
}
#submit{
	margin-top: 10px;
}
#link:link{
	color: blue;
	text-decoration: none;
}
#link:hover{
	text-decoration: underline;
}
#link:visited{
	color: purple;
}

register.php:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Register</title>
    <link rel="stylesheet" href="register.css">
    <?php
        function filter($input) {
            $input = trim($input);
            $input = stripslashes($input);
            $input = htmlspecialchars($input);
            return $input;
        }
        $conn = mysqli_connect("localhost", "root", "root") or die("Failed to connect to MySQL!");
        $seldb = mysqli_select_db($conn, "users") or die("Failed to connect to the database!");
        mysqli_query($conn, "set names 'utf8'");
        $username_err = "";
        $password0_err = "";
        $password1_err = "";
        $username = "";
        $password0 = "";
        $password1 = "";
        if (isset($_POST["submit"])) {
            $username = filter($_POST["username"]);
            $password0 = filter($_POST["password0"]);
            $password1 = filter($_POST["password1"]);
            if (empty($username)) $username_err = "Username cannot be empty!";
            else if (!preg_match("/^[a-zA-Z]+$/", $username)) $username_err = "Username can only contain letters!";
            if (empty($password0)) $password0_err = "Password cannot be empty!";
            else if (!preg_match("/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[\W_]).*$/", $password0)) $password0_err = "Password must contain letters, numbers, and special characters!";
            if (empty($password1)) $password1_err = "Confirm Password cannot be empty!";
            else if (!preg_match("/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[\W_]).*$/", $password1)) $password1_err = "Confirm Password must contain letters, numbers, and special characters!";
            if ($username_err == "" && $password0_err == "" && $password1_err == "") {
                if ($password0 === $password1) {
                    $search_query = "select * from password where username = '$username';";
                    $search_result = mysqli_query($conn, $search_query);
                    $search_result_array = mysqli_fetch_array($search_result);
                    if (!empty($search_result_array)) echo "<script>alert('Username is already taken!');</script>";
                    else {
                        $insert_query = "insert into password(username,password) values('$username','$password0');";
                        mysqli_query($conn, $insert_query);
                        echo "<script>alert('Register Success!');window.location.href='login.php';</script>";
                    }
                }
                else echo "<script>alert('Passwords do not match!');</script>";
            }
        }
    ?>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>REGISTER PAGE</h1>
    </div>
    <div class="content">
        <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="POST">
            <table>
                <tr>
                    <td><label for="username">Username</label></td>
                    <td><input type="text" id="username" name="username" value="<?php echo $username;?>"></td>
                    <td><span style="color: red; font-size: 12px;"><?php echo $username_err;?></span></td>
                </tr>
                <tr>
                    <td><label for="password0">Password</label></td>
                    <td><input type="password" id="password0" name="password0" value="<?php echo $password0;?>"></td>
                    <td><span style="color: red; font-size: 12px;"><?php echo $password0_err;?></span></td>
                </tr>
                <tr>
                    <td><label for="password1">Confirm Password</label></td>
                    <td><input type="password" id="password1" name="password1" value="<?php echo $password1;?>"></td>
                    <td><span style="color: red; font-size: 12px;"><?php echo $password1_err;?></span></td>
                </tr>
                <tr>
                    <td colspan="3" class="center-align">
                        <input type="submit" id="submit" name="submit" value="Register">
                    </td>
                </tr>
                <tr>
                    <td colspan="3" class="center-align">
                        Have an account? <a href="login.php" id="link">Login</a>
                    </td>
                </tr>
            </table>
        </form>
    </div>
</div>
</body>
</html>

register.css:

.container{
    text-align: center;
    margin-top: 200px;
}
table{
    margin: 0 auto;
}
#submit{
    margin-top: 10px;
}
#link:link{
    color: blue;
    text-decoration: none;
}
#link:hover{
    text-decoration: underline;
}
#link:visited{
    color: purple;
}

center.php:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Center</title>
    <link rel="stylesheet" href="center.css">
    <?php
        session_start();
        if (empty($_SESSION["username"])) echo "<script>alert('Please login first!');window.location.href='login.php';</script>";
        $username = $_SESSION["username"];
        $conn = mysqli_connect("localhost", "root", "root") or die("Failed to connect to MySQL!");
        $seldb = mysqli_select_db($conn, "users") or die("Failed to connect to the database!");
        mysqli_query($conn, "set names 'utf8'");
        if (isset($_POST["submit"])) {
            $username_new = $_POST["username_new"];
            $password_new = $_POST["password_new"];
            $update_query = "update password set username = '$username_new', password = '$password_new' where username = '$username';";
            mysqli_query($conn, $update_query);
            echo "<script>alert('Modify Success!');</script>";
        }
        $search_query = "select * from password where username = '$username';";
        $search_result = mysqli_query($conn, $search_query);
        $search_result_array = mysqli_fetch_array($search_result);
        if (isset($_POST["logout"])) {
            session_unset();
            session_destroy();
            echo "<script>alert('Logout Success!');window.location.href='login.php';</script>";
        }
    ?>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>Welcome, <?php echo $search_result_array['username'];?>!</h1>
    </div>
    <div class="content">
        <form action="#" method="POST">
            <table>
                <tr>
                    <td><label for="username">Username</label></td>
                    <td><input type="text" id="username" name="username_new" value="<?php echo $search_result_array['username'];?>"></td>
                </tr>
                <tr>
                    <td><label for="password">Password</label></td>
                    <td><input type="password" id="password" name="password_new" value="<?php echo $search_result_array['password'];?>"></td>
                </tr>
                <tr>
                    <td colspan="2" class="center-align">
                        <input type="submit" id="submit" name="submit" value="Modify">
                    </td>
                </tr>
                <tr>
                    <td colspan="2" class="center-align">
                        <input type="submit" id="logout" name="logout" value="Logout">
                    </td>
                </tr>
            </table>
        </form>
    </div>
</div>
</body>
</html>

center.css:

.container{
	text-align: center;
	margin-top: 200px;
}
table{
    margin: 0 auto;
}
#submit{
	margin-top: 10px;
}

个人中心页面:

posted @ 2024-06-26 20:30  yaoguyuan  阅读(10)  评论(0编辑  收藏  举报