-
Hajipur, Bihar, 844101
Sessions are a way to store information about users on the server rather than in their browser. Unlike cookies, which are stored on the client side, sessions allow you to save data securely for individual users across multiple pages. They are widely used for login systems, shopping carts, and any feature that requires user-specific data to persist during a visit.
A session in PHP stores data in a special server-side storage and associates it with a unique session ID. This session ID is sent to the user’s browser in the form of a small cookie named PHPSESSID
. Each time the user navigates to another page on the site, PHP uses this session ID to retrieve the stored data. This allows information like login status, shopping cart items, or preferences to remain consistent across multiple page requests.
A user visits a PHP page.
PHP creates a unique session ID and sends it to the browser.
Session data is stored on the server.
Each subsequent page request includes the session ID, allowing PHP to retrieve the corresponding data.
When the user closes the browser or the session times out, the session data is removed.
Before using sessions, you must start them using session_start()
.
<?php
session_start();
// Store session variables
$_SESSION["username"] = "Vrinda";
$_SESSION["role"] = "Admin";
echo "Session started. Data saved.";
?>
Always call session_start()
before any HTML output.
$_SESSION
is an associative array used to store session variables.
You can store multiple key-value pairs as needed.
Session variables can be accessed from any page, provided the session is started.
<?php
session_start();
echo "Username: " . $_SESSION["username"] . "<br>";
echo "Role: " . $_SESSION["role"];
?>
PHP retrieves the data associated with the session ID, allowing you to maintain consistent user information.
You can update the value of a session variable by reassigning it.
<?php
session_start();
$_SESSION["role"] = "Editor";
echo "User role updated to: " . $_SESSION["role"];
?>
Changes are stored on the server and persist until the session ends.
To remove a specific session variable:
<?php
session_start();
unset($_SESSION["role"]);
echo "Session variable 'role' removed.";
?>
This removes only the specified variable, keeping other session data intact.
To end a session completely and delete all stored data:
<?php
session_start();
session_unset(); // Clear all session variables
session_destroy(); // Destroy the session
echo "Session destroyed successfully.";
?>
After this, the session ID is invalid, and any previously stored data is no longer accessible.
login.php
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
$password = $_POST["password"];
if ($username == "Ritika" && $password == "12345") {
$_SESSION["username"] = $username;
header("Location: welcome.php");
} else {
echo "Invalid login credentials!";
}
}
?>
<form method="post">
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password" required><br>
<input type="submit" value="Login">
</form>
welcome.php
<?php
session_start();
if (!isset($_SESSION["username"])) {
header("Location: login.php");
exit;
}
echo "Welcome, " . $_SESSION["username"] . "!<br>";
echo "<a href='logout.php'>Logout</a>";
?>
logout.php
<?php
session_start();
session_destroy();
echo "You have been logged out.";
?>
This demonstrates a simple login system where a session keeps the user logged in across pages and allows proper logout handling.
PHP sessions have a default timeout (often 24 minutes) but can be configured:
session.gc_maxlifetime = 3600
This sets session data to expire after 1 hour. You can also manage session timeouts within your scripts by checking the last activity time and destroying the session manually after inactivity.
Session data is stored on the server, usually in temporary files. You can check or change the storage location:
echo session_save_path(); // Current path
session_save_path("/home/user/sessions"); // Change path
session_start();
This is helpful when you need to store sessions securely or on a different server.
Always start sessions before output.
Regenerate session IDs after login to prevent session fixation:
session_regenerate_id(true);
Use HTTPS to secure session cookies.
Avoid storing sensitive data directly in session variables.
Clear sessions properly on logout.
PHP sessions allow secure server-side storage of user data across multiple pages. They differ from cookies in that the information is stored on the server rather than the client, making them more secure. By using session_start()
, $_SESSION
, unset()
, and session_destroy()
, developers can create persistent, user-specific data like login information or shopping carts. Sessions have configurable timeouts and can be stored in secure server directories. Understanding session management is essential for building reliable, interactive, and secure web applications.
Start a PHP session and store the username "Vrinda"
and role "Admin"
in session variables.
Write PHP code to check if a session variable username
exists, and display a welcome message if it does.
Update the session variable role
to "Editor"
and display the new value.
Remove only the session variable role
without affecting other session data.
Destroy a session completely and display a message confirming the session is destroyed.
Create a simple login system using sessions where the username is "Ritika"
and password is "12345"
.
Write a PHP script to prevent access to a page if the session variable username
is not set.
Regenerate the session ID after login to enhance security.
Store a timestamp in a session variable and automatically destroy the session after 10 minutes of inactivity.
Display all session variables using a loop and show their names and values.