In PHP, sessions provide a way to persist data across multiple page requests for a single user. Storing data in a session allows developers to maintain user-specific information such as login status, user preferences, shopping cart items, etc.
Syntax:
// Start or resume a session
session_start();
// Store data in the session
$_SESSION['key'] = $value;
Important:
-
Before storing or accessing session data, it’s essential to start or resume the session using
session_start()
. -
Data is stored in the
$_SESSION
superglobal array, using associative keys to identify the stored values. - Session data persists until the session is explicitly destroyed or expires due to inactivity.
$_SESSION | Cookies |
---|---|
Stores data on the server side | Stores data on the client side |
Persists until the session ends | Can have an expiration date |
Suitable for sensitive data | Limited in size and can be manipulated by the client |
Usage
- Use sessions to store user authentication information such as user ID, username, or login status to maintain user sessions across multiple pages.
Example: Upon successful login, store the user ID in the session to authenticate subsequent page requests.
- Utilize sessions to store shopping cart items, quantities, and prices to maintain the state of the user’s shopping cart across page requests.
Example: Store the selected items and quantities in the session as the user adds products to the cart, allowing seamless navigation between different pages while preserving the shopping cart contents.