且构网

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

PHP会话或cookie

更新时间:2023-11-28 11:12:34

由于PHP会话实际上通过cookie存储SID(当然,如果你喜欢,可以使用其他方式设置SID ),只是简单地使用它们没有什么区别。



主要区别是安全性,因为如果你使用cookies直接客户端可以看到和/但是对于会话,数据存储在服务器端,因此客户端无法直接访问。



因此,如果数据只持续会话,我更喜欢使用会话。 >

注意:如果您使用多个服务器来平衡负载,您应该非常小心,因为会话数据默认存储在服务器本地。可以跨多个服务器共享会话数据,但这是超出这个问题的范围。或者,您可以将数据存储在数据库中。


What's best way to keep user logged on a PHP-powered site until he closes his browser?

The first and the most popular way is to go with $_SESSION. The second is to pass zero as the third argument of setcookie function: setcookie(name, value, 0, domain);

As PHP session actually stores the SID by cookie (of course you can use other ways to set the SID if you like), there would not be much difference when simply using them.

The main difference is security, because if you use cookies directly clients can see and/or edit them themselves, but for session the data is stored on the server side so client cannot access directly.

So if the data only lasts for that session, I prefer using session.

Side-note: if you use multiple servers to balance the load you should be extremely careful because session data is stored locally on the server by default. It is possible to share session data across multiple servers but this is beyond the scope of this question. Alternatively, you can store data in a database.