php session vs cookie code example

Example: cookies vs session

Detailed answer
Cookies
Cookies are stored on the client side (in the visitor's browser).
Cookies are not safe: it's quite easy to read and write cookie contents.
When using cookies, you have to notify visitors according to european laws (GDPR).
Expiration can be set, but user or browser can change it.
Users (or browser) can (be set to) decline the use of cookies.
Sessions
Sessions are stored on the server side.
Sessions use cookies (see below).
Sessions are safer than cookies, but not invulnarable.
Expiration is set in server configuration (php.ini for example).
Default expiration time is 24 minutes or when the browser is closed.
Expiration is reset when the user refreshes or loads a new page.
Users (or browser) can (be set to) decline the use of cookies, therefore sessions.
Legally, you also have to notify visitors for the cookie, but the lack of precedent is not clear yet.
The appropriate choice
Sessions use a cookie! Session data is stored on the server side, but a UID is stored on client side in a cookie. It allows the server to match a given user with the right session data. UID is protected and hard to hack, but not invulnarable. For sensitive actions (changing email or resetting password), do not rely on sessions neither cookies : ask for the user password to confirm the action.

Sensitive data should never be stored in cookies (emails, encrypted passwords, personal data ...). Keep in mind the data are stored on a foreign computer, and if the computer is not private (classroom or public computers) someone else can potentially read the cookies content.

Remember-me data must be stored in cookies, otherwise data will be lost when the user closes the browser. However, don't save password or user personal data in the 'remember-me' cookie. Store user data in database and link this data with an encrypted pair of ID / key stored in a cookie.

After considering the previous recommandations, the following question is finally what helps you choosing between cookies and sessions:

Must persistent data remain when the user closes the browser ?

If the answer is yes, use cookies.
If the answer is no, use sessions.
Source : https://www.lucidar.me/en/web-dev/sessions-or-cookies/

Tags:

Misc Example