What is Session in PHP: Explanation and Example
session in PHP is a way to store information (variables) to be used across multiple pages by the same user. It keeps data on the server and uses a unique session ID to link the user to their stored data during their visit.How It Works
Think of a session like a temporary locker assigned to a visitor when they enter a website. This locker holds their personal items (data) safely while they browse different pages. PHP creates a unique session ID for each visitor, which acts like the locker key.
When the visitor moves to another page, PHP uses the session ID to find their locker and access the stored data. This way, the website remembers who the visitor is and what they did, without asking them to log in or enter information again on every page.
The session data is stored on the server, so it is more secure than storing data in the browser. The session ends when the visitor leaves the site or after a set time of inactivity.
Example
This example shows how to start a session, store a value, and then retrieve it on another page.
<?php // Start the session session_start(); // Store data in session variable $_SESSION['username'] = 'Alice'; // Retrieve and display the stored session data if(isset($_SESSION['username'])) { echo 'Hello, ' . $_SESSION['username'] . '!'; } else { echo 'No session data found.'; } ?>
When to Use
Use sessions when you want to remember information about a user while they browse your website. Common uses include:
- Keeping users logged in after they enter their username and password.
- Saving items in a shopping cart before checkout.
- Storing user preferences like language or theme.
- Tracking progress in multi-step forms or quizzes.
Sessions help create a smooth and personalized experience without forcing users to re-enter data on every page.
Key Points
- Sessions store data on the server, linked by a unique session ID.
- Session data persists across multiple pages during a user's visit.
- Sessions are more secure than cookies for sensitive data.
- Always call
session_start()before accessing session variables. - Sessions expire after inactivity or when explicitly destroyed.
Key Takeaways
session_start() to begin or resume a session before accessing session variables.