Practical – 8
Aim :- Practical exercise to save the user session on server side.
PHP Program: session_demo.php
<?php
// Step 1: Start session
session_start();
// Step 2: Store values in session
if (!isset($_SESSION['username'])) {
$_SESSION['username'] = "Ashish"; // Example value
$_SESSION['role'] = "Student";
$message = "New session started. Data saved on the server.";
} else {
$message = "Session already exists. Data retrieved from server.";
?>
<!DOCTYPE html>
<html>
<head>
<title>Session Demo</title>
</head>
<body>
<h2>PHP Session Example</h2>
<p><?php echo $message; ?></p>
<h3>Session Data:</h3>
<p>Username: <?php echo $_SESSION['username']; ?></p>
<p>Role: <?php echo $_SESSION['role']; ?></p>
<p><a href="session_destroy.php">End Session</a></p>
</body>
</html>
File 2: session_destroy.php
<?php
session_start();
session_unset(); // remove all session variables
session_destroy(); // destroy the session
?>
<!DOCTYPE html>
<html>
<head>
<title>Session Destroyed</title>
</head>
<body>
<h2>Session has been destroyed.</h2>
<p><a href="session_demo.php">Start Again</a></p>
</body>
</html>
How to Run (Exercise Steps)
1. Open session_demo.php in the browser.
o First time → session variables are created on the server.
o Output:
New session started. Data saved on the server.
Username: Ashish
Role: Student
2. Refresh the page again.
Session is already active, so values are retrieved:
Session already exists. Data retrieved from server.
Username: Ashish
Role: Student
3. Click “End Session” link.
Opens session_destroy.php, clears session data.
Output:
Session has been destroyed.
4. Go back to session_demo.php → A new session is created again.