Introduction to Sessions in PHP
A session in PHP is a way to store user information across multiple pages of a website. Unlike cookies, which store data on the client’s browser, session data is stored on the server, making it more secure.
Sessions are widely used for tasks such as:
- User authentication (login/logout functionality).
- Storing user preferences.
- Shopping carts in e-commerce websites.
- Temporary storage of user data between different web pages.
How Sessions Work in PHP
A session starts when a user visits a website, and a unique Session ID is assigned to the user. This ID is stored in a cookie called PHPSESSID on the user’s browser, while the actual session data is stored on the server. Every time the user requests a new page, the session ID is sent to the server, allowing the server to retrieve the stored session data.
Session Workflow in PHP
- User requests a webpage.
- PHP starts a session (session_start()).
- A unique session ID is generated and stored in the browser.
- Session variables are stored on the server.
- User navigates to another page, and PHP retrieves session data using the session ID.
- Session ends when the user logs out or the session expires.
Starting a Session in PHP
To use sessions, you must start a session on every page that needs to access session data. This is done using session_start().
Example: Starting a Session and Storing Data
<?php
session_start(); // Start the session
$_SESSION[“username”] = “JohnDoe”; // Store data in session
$_SESSION[“email”] = “john@example.com”;
echo “Session variables are set.”;
?>
- session_start() must be called at the beginning of the script before any HTML output.
- $_SESSION[“key”] = value; stores session data in an associative array.
Accessing Session Variables
To retrieve session data, use $_SESSION on any page after calling session_start().
Example: Retrieving Session Data
<?php
session_start(); // Start the session
echo “Username: ” . $_SESSION[“username”] . “<br>”;
echo “Email: ” . $_SESSION[“email”];
?>
Output:
Username: JohnDoe
Email: john@example.com
Destroying a Session
To end a session and remove all session data, use session_destroy() and session_unset().
Example: Destroying a Session
<?php
session_start(); // Start the session
session_unset(); // Remove all session variables
session_destroy(); // Destroy the session
echo “Session destroyed.”;
?>
- session_unset(); clears all session variables.
- session_destroy(); completely removes the session.
Regenerating Session ID for Security
For security reasons, it’s a good practice to regenerate the session ID after login or periodically to prevent session hijacking.
Example: Regenerating Session ID
<?php
session_start(); // Start the session
session_regenerate_id(true); // Generate a new session ID
echo “New session ID generated.”;
?>
Setting Session Lifetime and Configuration
By default, sessions expire when the user closes the browser. However, you can configure the session lifetime.
Setting a Custom Session Lifetime
Modify php.ini or set session timeout in your script:
<?php
session_start(); // Start session
// Set session timeout to 30 minutes (1800 seconds)
ini_set(‘session.gc_maxlifetime’, 1800);
session_set_cookie_params(1800);
?>
Alternatively, modify php.ini:
session.gc_maxlifetime = 1800
Session vs Cookies: Key Differences
Feature | Sessions | Cookies |
Storage | Stored on the server | Stored on the client’s browser |
Security | More secure (data is not exposed to the user) | Less secure (user can modify data) |
Lifetime | Expires when the browser is closed (unless configured) | Can have an expiration time set |
Capacity | Can store large amounts of data | Limited to 4KB |
Accessibility | Accessible only on the server | Accessible on both server and client |
Use Cases of Sessions in PHP
- User Login System – Store username and authentication status.
- Shopping Cart – Maintain cart items across different pages.
- Form Data Persistence – Keep form inputs stored across multiple steps.
- User Preferences – Save user-selected language, theme, etc.
Example: User Login with Sessions
1. login.php (User Login and Start Session)
<?php
session_start(); // Start the session
// Simulated user authentication
$username = “admin”;
$password = “password123”;
if ($_POST[“username”] == $username && $_POST[“password”] == $password) {
$_SESSION[“user”] = $username;
echo “Login successful! <a href=’dashboard.php’>Go to Dashboard</a>”;
} else {
echo “Invalid credentials.”;
}
?>
<form method=”post”>
Username: <input type=”text” name=”username”><br>
Password: <input type=”password” name=”password”><br>
<input type=”submit” value=”Login”>
</form>
2. dashboard.php (Accessing Session Data)
<?php
session_start();
if (!isset($_SESSION[“user”])) {
echo “Access Denied. <a href=’login.php’>Login</a>”;
exit();
}
echo “Welcome, ” . $_SESSION[“user”] . “! <a href=’logout.php’>Logout</a>”;
?>
3. logout.php (Destroying Session on Logout)
<?php
session_start();
session_unset();
session_destroy();
echo “Logged out. <a href=’login.php’>Login again</a>”;
?>
Conclusion
Sessions in PHP provide a secure and efficient way to store user-specific data across web pages. Unlike cookies, session data is stored on the server, making it more secure for handling sensitive information. Using sessions, developers can implement functionalities such as user authentication, shopping carts, and persistent user preferences.