言成言成啊 | Kit Chen's Blog

cookie与session的区别

发布于2020-04-08 19:16:25,更新于2023-10-29 10:25:20,标签:http web  转载随意,文章会持续修订,请注明来源地址:https://meethigher.top/blog

一、Cookie

HTTP 很重要的一个特点就是无状态(每一次见面都是“初次见面”),如果单纯的希望通过我们的服务端程序去记 住每一个访问者是不可能的,所以必须借助一些手段或者说技巧让服务端记住客户端,这种手段就是 Cookie

Cookie 就像是在超级市场买东西拿到的小票,由超市(Server)发给消费者(Browser),超市方面不用记住每一个消费者的脸,但是他们认识消费者手里的小票(Cookie),可以通过小票知道消费者之前的一些消费信息(在服务端产生的数据)。

二、Session

由于 Cookie 是服务端下发给客户端由客户端本地保存的。换而言之客户端可以在本地对其随意操作,包括删除和修改。如果客户端随意伪造一个 Cookie 的话,对于服务端是无法辨别的,就会造成服务端被蒙蔽,构成安全隐患。 于是乎就有了另外一种基于Cookie 基础之上的手段:Session。

Session区别于 Cookie一个很大的地方就是:Session 数据存在了服务端,而 Cookie 存在了客户端本地,存在服务端最大的优势就是,不是用户想怎么改就怎么改了。

Session 这种机制会更加适合于存放一些属于用户而又不能让用户修改的数据,因为客户端不再保存具体的数据, 只是保存一把“钥匙”。伪造一把可以用的钥匙,可能性是极低的,所以不需要在意。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String str = (String) application.getAttribute("count01");
int total = 0;
if (str == null) {
total = 1;
} else {
total = Integer.parseInt(str) + 1;
}
if (session.isNew()) {
out.println("你是第一次访问这个网站");
}
application.setAttribute("count01", total + "");
%>
<p>
你是第<%=application.getAttribute("count01")%>个访问该网站
</p>
</body>
</html>

上面这个例子,是通过jsp的application对象,来实现一个网站的访问统计。

application在服务器开启之后,就会存在;在服务器关闭之后,数据就会清零。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<?php
$countFile = "count.txt";
if (!file_exists($countFile)) {
$count = 0;
$cf = fopen($countFile, "w");
fputs($cf, $count);
fclose($cf);
} else {
$cf = fopen($countFile, "r");
$count = (int)trim(fgets($cf));
fclose($cf);
}


$count++;
$cf = fopen($countFile, "w");
fputs($cf, $count);
fclose($cf);

?>
你是第<?php echo $count ?>个访问的
</body>
</html>

php通过文件来统计的话,也是可以实现这个功能的

发布:2020-04-08 19:16:25
修改:2023-10-29 10:25:20
链接:https://meethigher.top/blog/2020/cookie-and-session/
标签:http web 
付款码 打赏 分享
shift+ctrl+1可控制目录显示