![](https://img-blog.csdnimg.cn/img_convert/2f682405f8c62ebf345bc22ac6f58735.png)
代码实现
首页代码
<html>
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>
欢迎
<?php
session_save_path('.');
session_start();
echo $_SESSION['username'];
?>
进入首页!
</h1>
<br>
<a href="denglu.php">登录</a>
</body>
</html>
登录代码
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form method="get" action="houtai.php">
用户名:<input type="text" name="username">
密码:<input type="password" name="password">
<input type="submit" value="submit">
</form>
</body>
</html>
后台代码
<?php
$username=$_GET["username"];
$password=$_GET["password"];
if ($username=="root"&&$password=="root"){
session_save_path(".");
session_start();
$_SESSION['username']=$username;
echo '用户名密码输入正确,即将跳转到首页';
header("Refresh:3,url='./shouye.php'");//使用header函数刷新页面
}
else{
echo '用户名或密码错误,即将跳转到登录界面,请重新输入';
header('Refresh:3,url="./denglu.php"');
}
![](https://img-blog.csdnimg.cn/img_convert/e0e8c479f808d0a15bb22ae189c5329d.png)
当用户第一次进入首页时,即第一次访问网站时,是没有cookie值的。
点击登录进入登录网页
![](https://img-blog.csdnimg.cn/img_convert/1a9806987579e6cda803b3d0cf7a8066.png)
输入用户名和密码,进入网站后台
如果输入错误,跳转到登录页面重新输入用户名和密码,也不会生成session凭证
![](https://img-blog.csdnimg.cn/img_convert/bf71eb4b604e71ee67000235d6af7aa9.png)
如果输入正确的用户名和密码,生成session凭证,并跳转至首页
请求包
![](https://img-blog.csdnimg.cn/img_convert/26c4f7c95c7fc99cec4833eef2ddfbff.png)
响应包
![](https://img-blog.csdnimg.cn/img_convert/76d4f89f1d8341f8fdbfe4132dd587b5.png)
可以看到,服务器端返回给浏览器set-cookie值。cookie就是服务器端存储的session凭证的文件名。
![](https://img-blog.csdnimg.cn/img_convert/ff564ac8c999f79c819e20db87468406.png)
该文件中存储的用户登录状态
cookie值存储在浏览器中
![](https://img-blog.csdnimg.cn/img_convert/cca47ba1f4d61bd779cc0558f049156f.png)
当用户下一次登录时,带上cookie字段
![](https://img-blog.csdnimg.cn/img_convert/fc085457a30aa6bb74a1bc722d61e7e7.png)
就不用再次输入用户名和密码了。
安全问题
当攻击者拿到浏览器cookie值时,不用知道管理员用户名和密码就可以登录网站,这是不安全的。
![](https://img-blog.csdnimg.cn/img_convert/9819cf7ff741d2338e910d35251c2fd0.png)
攻击者将cookie值改为用户登录的cookie值,直接获得用户登录状态。
![](https://img-blog.csdnimg.cn/img_convert/eb8ab78e404ca4674972908c4c4168f7.png)