且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我在用PHP做在线测验类型的脚本.***使用Cookie或会话

更新时间:2023-02-07 17:07:32

cookie和会话之间的主要区别在于数据的存储位置.

The main difference between cookies and sessions is where the data is stored.

使用Cookie,您可以将数据发送到浏览器,然后浏览器会在以后的每次请求中不断将数据发送回给您.

With cookies, you send the data to the browser, and the browser keeps sending it back to you with every request thereafter.

对于会话,您将数据存储在内存中,然后仅设置一个具有ID的cookie,以标识服务器内存中存储数据的空间块.

With sessions, you're storing the data in memory, and then just setting one cookie that has an ID to identify the chunk of space in the server's memory where the data is stored.

关键区别在于,当数据存储在cookie中时:

The crucial difference is that when the data is stored in cookies:

  • 它可以由用户编辑
  • 在网络上可以看到它发出的请求
  • 它增加了每个请求的权重,需要额外的带宽
  • 占用更少的服务器内存

在会话中存储数据时:

  • 用户无法浏览它就无法访问
  • 它不会与每个请求来回发送(只有会话ID cookie)
  • 但是它占用了服务器上的内存
  • 当需要移至多个Web服务器时,它可能会在较大的站点上引起问题

我会说这取决于规模.对于很多问题,这些cookie会变得很重,并且使每个请求都非常大.如果您的测验是在分布于多个前端Web服务器上的环境中运行,则会话可能就不存在了.

I would say it depends on scale. For a lot of questions, those cookies will get heavy and make each request very large. If you quiz is running in an environment that is spread across multiple front-end web servers, sessions might be out of the question.

我怀疑决定因素将是测验的完整性.如果至关重要的是用户不能更改数据(例如以前的答案,分数运行或测验开始的时间戳),则需要将数据存储在他们无法到达的范围内,这意味着要使用会话.

I suspect the deciding factor is going to be the integrity of the quiz though. If it's crucial that the user can't change the data (such as previous answers, a running score or a timestamp for the start of the quiz) then you'll need to store the data out of their reach, which means using sessions.