1

I was wondering if using a SESSION variable to pass data from one PHP page to another is efficient. I ask this because I thought that SESSIONS were only used to keep the user logged in to a website, and as an alternative to cookies. Would it not be better to pass data (non-sensitive) from one page to another via a URI such as members.php?name=Joe&age=28?

4

4 回答 4

5

A PHP session writes a cookie to your browser and then stores the data associated with that session on disk; its about as expensive as an include() to read it back in on the next page load, which is to say completely trivial.

Additionally, the user can't change session data unless you create a mechanism which allows them to; they can mess with the query string easily.

Short answer: Yes, its efficient.

于 2013-02-06T18:33:23.380 回答
2

Depends on what you're doing. If that page requires that information to function properly and is not behind a login then passing in a query string is the way to go (e.g. search results, product pages). If it is behind a login then using a session would allow you to keep your URLs clean and also make it difficult for users to abuse the page (e.g. swap out data in the query string).

于 2013-02-06T18:32:55.430 回答
2

会话对很多事情都很有用,而不仅仅是登录信息。它们非常适合在 POST/redirect/GET 周期或任何其他跟踪用户会话状态的状态消息(因此得名) - 但仅限于当前会话,而不是长期永久配置选项。

就效率而言,您需要记住会话中的任何内容都需要在每次页面加载时进行序列化和反序列化。存储姓名和年龄不会增加太多。添加一兆字节的图像上传可能会很糟糕。

比效率考虑更重要的是要记住会话数据只是暂时持久的。如果您想始终知道 Joe 是 28 岁,则应该将其放入数据库中。如果它仅在单个页面加载时有用,它可能应该保留在 URL 中或被发布。如果你有兴趣记住它几分钟,会话可能是放置它的地方。

于 2013-02-06T18:39:48.910 回答
0

是的,您可以将数据和消息存储在 SESSION 中,并且可以从任何页面访问。但请记住,SESSION 使用浏览器支持来存储数据。它们可以由用户手动删除

于 2013-02-06T18:36:10.847 回答