A session is a way to store information (or data) about a user across multiple pages or interactions with a website. It allows you to maintain user-specific data throughout a browsing session.
Session store data server side
Session Work Flow:
Sessions work in PHP:
1. Session Start:
To start a session, you use the session_start() function at the beginning of your PHP script. This function initialise a session.
<?php
session_start();
?>
2. Session Data:
Once the session is started, you can store data in the $_SESSION super global array. This array persists across multiple pages requests within the same session.
<?php
// Storing data in session
$_SESSION['username'] = 'john123';
$_SESSION['user_id'] = 12345;
?>
3. Accessing Session Data:
You can access session data anywhere in your PHP script by using the $_SESSION super global array.
<?php
// Accessing session data
echo "Welcome, " . $_SESSION['username'];
echo "Your user ID is: " . $_SESSION['user_id'];
?>
4. Session Termination:
When the user closes the browser or the session expires the session data is destroyed.
<?php
// Destroying the session
session_destroy();
?>