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:
- Start: Call
session_start()at the very beginning of the script. - Set: Store data in the
$_SESSIONsuperglobal. - Unset/Destroy: Use
unset()orsession_destroy()to log out.
php