Session is a way to store information on the server to be used across multiple pages of a web application.
- Unlike cookies, which store data on the client-side, PHP sessions keep data on the server, providing a more secure and efficient way to maintain state for individual users.
Characteristics:
- Session data is stored on the server, making it more secure.
- It is suitable for storing sensitive information such as login credentials and user preferences.
- It has no storage limit.
- Data stored in a session is accessible across multiple pages.
- Data remains on the server, ensuring that critical information is not visible or modifiable by the client.
- Sessions allow easy tracking of user activities, such as login status, navigation history, and temporary preferences.
Starting a Session
To use sessions, first call session_start(
) at the beginning of your script. This initializes a session or resumes the current one if it already exists.
<?php
session_start(); // Start a new session or resume an existing one
?>
Setting Session Variables
Once a session is started, you can store data in session variables using the $_SESSION
superglobal array. These variables are accessible across pages.
<?php
session_start();
$_SESSION['username'] = 'JohnDoe';
$_SESSION['role'] = 'admin';
?>
Accessing Session Variables
To retrieve session data, you need to start the session using session_start(), then access session variables via $_SESSION.
<?php
session_start();
echo "User: " . $_SESSION['username'];
echo "Role: " . $_SESSION['role'];
?>
Ending a Session
To end a session and remove all session data, use session_destroy(). You can also unset specific session variables with unset().
<?php
session_start();
// Unset a single session variable
unset($_SESSION['username']);
// Destroy all session data
session_destroy();
?>
Session Timeout in PHP
You can set a session timeout by configuring the session.gc_maxlifetime setting in php.ini, or you can implement a custom timeout by storing the user’s last activity timestamp in the session.
<?php
session_start();
$timeout_duration = 1800; // 30 minutes
// Check if 'last_activity' is set in the session
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > $timeout_duration) {
session_unset(); // Unset session variables
session_destroy(); // Destroy session data
header("Location: login.php"); // Redirect to login page
}
$_SESSION['last_activity'] = time();
?>