PHP session or cookie

treng picture treng · Jun 22, 2012 · Viewed 17.5k times · Source

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);

Answer

Alvin Wong picture Alvin Wong · Jun 22, 2012

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.