Open In App

How to store data in a PHP Session?

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:

$_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

Example: Upon successful login, store the user ID in the session to authenticate subsequent 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.

Article Tags :