PHP sessions allow a website to store user-related data on the server across multiple requests. They are commonly used for login systems, shopping carts, and temporary user information.
HTTP requests are independent. Sessions help PHP associate multiple requests with the same session data.
Session data is generally stored on the server. The browser typically holds a session identifier in a cookie, which PHP uses to locate the corresponding session data.
Do not assume session data lasts forever. Its lifetime depends on session configuration, cleanup, and application behavior.
The session_start() function starts a new
session or resumes an existing one.
<?php
session_start();
echo "PHP session started successfully.";
?>
Output: PHP session started successfully.
Call session_start() before sending HTML,
whitespace, or other output to the browser when PHP needs
to send session headers.
If your website already starts sessions in a shared header file, avoid starting the same session again without checking whether one is active.
<?php
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
echo "Session is ready.";
?>
The $_SESSION superglobal stores values
associated with the current session.
<?php
session_start();
$_SESSION["username"] = "Rahul";
$_SESSION["course"] = "PHP Programming";
$_SESSION["student_id"] = 101;
echo "Session data saved.";
?>
Output: Session data saved.
You can store strings, numbers, arrays, and other serializable values in a session.
Session data is stored on the server in typical PHP configurations, but it should still be handled carefully. Avoid storing unnecessary sensitive information.
Once a session has been started, you can read its values
using the $_SESSION array.
<?php
session_start();
if (isset($_SESSION["username"])) {
echo "Welcome, " . htmlspecialchars(
$_SESSION["username"],
ENT_QUOTES | ENT_SUBSTITUTE,
"UTF-8"
);
} else {
echo "Please log in first.";
}
?>
Example output: Welcome, Rahul
The output assumes the username was previously stored in the same session.
<?php
session_start();
$course = $_SESSION["course"] ?? "No course selected";
echo htmlspecialchars(
$course,
ENT_QUOTES | ENT_SUBSTITUTE,
"UTF-8"
);
?>
The null coalescing operator (??) supplies
a default value when the session key is missing or null.
You can update session values by assigning new values to existing keys.
<?php
session_start();
$_SESSION["username"] = "Rahul";
$_SESSION["course"] = "PHP Programming";
$_SESSION["course"] = "Full Stack Development";
echo "Course updated to: " . htmlspecialchars(
$_SESSION["course"],
ENT_QUOTES | ENT_SUBSTITUTE,
"UTF-8"
);
?>
Output: Course updated to: Full Stack Development
Session changes are available to subsequent requests associated with the same session.
For login systems, never trust a session value merely because it exists. Verify authorization and permissions on the server before allowing access to protected resources.
Use unset() to remove a particular session
variable without deleting every other session value.
<?php
session_start();
$_SESSION["username"] = "Rahul";
$_SESSION["course"] = "PHP";
unset($_SESSION["course"]);
if (isset($_SESSION["course"])) {
echo "Course is available.";
} else {
echo "Course session variable removed.";
}
?>
Output: Course session variable removed.
Use unset($_SESSION["key"]) when you want
to remove only one value.
This does not destroy the entire session or necessarily remove the browser's session cookie.
The session_destroy() function destroys the
session data associated with the current session.
<?php
session_start();
$_SESSION = [];
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), "", [
"expires" => time() - 42000,
"path" => $params["path"],
"domain" => $params["domain"],
"secure" => $params["secure"],
"httponly" => $params["httponly"],
"samesite" => $params["samesite"] ?? "Lax"
]);
}
session_destroy();
echo "Session has been logged out.";
?>
This example clears the current session data and expires the session cookie using its configured parameters.
A session logout should also revoke any related authentication state managed elsewhere in the application. Call this code before sending page output.
This is a simple learning example demonstrating how session variables can represent a login state. It uses hardcoded demo credentials and is not a production authentication system.
<?php
session_start();
$error = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$username = $_POST["username"] ?? "";
$password = $_POST["password"] ?? "";
if ($username === "rahul" && $password === "demo123") {
session_regenerate_id(true);
$_SESSION["username"] = "Rahul";
$_SESSION["logged_in"] = true;
header("Location: dashboard.php");
exit;
} else {
$error = "Invalid username or password.";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Session Login</title>
</head>
<body>
<h2>Login Form</h2>
<form method="post">
<label for="username">Username:</label>
<input type="text"
id="username"
name="username"
required>
<br><br>
<label for="password">Password:</label>
<input type="password"
id="password"
name="password"
required>
<br><br>
<button type="submit">Login</button>
</form>
<p>
<?= htmlspecialchars(
$error,
ENT_QUOTES | ENT_SUBSTITUTE,
"UTF-8"
) ?>
</p>
</body>
</html>
Demo credentials: username rahul,
password demo123.
In a real application, retrieve users from a database,
store password hashes using password_hash(),
verify them using password_verify(), and
use HTTPS with secure session-cookie settings.
<?php
session_start();
if (empty($_SESSION["logged_in"])) {
header("Location: login.php");
exit;
}
$username = $_SESSION["username"] ?? "User";
?>
<h2>Welcome,
<?= htmlspecialchars(
$username,
ENT_QUOTES | ENT_SUBSTITUTE,
"UTF-8"
) ?>
</h2>
<p>You are logged in.</p>
<a href="logout.php">Logout</a>
The dashboard checks the session on the server before showing protected content. Use a consistent login filename and create a logout page to complete the exercise.
Follow these practices when using sessions:
Session configuration example:
<?php
ini_set("session.use_only_cookies", "1");
ini_set("session.use_strict_mode", "1");
session_set_cookie_params([
"lifetime" => 0,
"path" => "/",
"secure" => true,
"httponly" => true,
"samesite" => "Lax"
]);
session_start();
echo "Session started with secure cookie options.";
?>
Configure session settings before calling
session_start() and before output.
The secure option requires HTTPS; adjust it for local
HTTP development. Production settings should be configured
centrally and consistently across the application.
1. Which function starts or resumes a PHP session?
2. Which superglobal stores session variables?
3. Which function destroys the current session data?