Back to course

Sessions and Cookies: Managing User State ($\_SESSION, $\_COOKIE)

PHP: The Complete 0 to Hero Bootcamp

30. Sessions and Cookies: Managing User State

HTTP is a stateless protocol, meaning the server forgets everything about the user between requests. Sessions and Cookies are mechanisms used to persist data and maintain the user's state (e.g., staying logged in, cart contents).

1. Cookies

  • Small files stored directly on the user's computer by the browser.
  • Used for non-sensitive settings (preferences, tracking).
  • Can expire after a set time.

Setting a Cookie:

php

Accessing Cookies: Use the $_COOKIE superglobal.

php

2. Sessions (Recommended for Logins)

  • Data is stored securely on the server.
  • Only a unique Session ID is stored on the user's computer (usually via a temporary cookie).
  • Session data is typically destroyed when the user closes the browser or after a period of inactivity.

Session Steps:

  1. Start: Call session_start() at the very beginning of the script.
  2. Set: Store data in the $_SESSION superglobal.
  3. Unset/Destroy: Use unset() or session_destroy() to log out.

php