Introduction
Sessions in PHP allow websites to store user information on the server and access it across multiple pages. They are commonly used for login systems, shopping carts, and user authentication. In this chapter, you will practise starting sessions, storing and retrieving session variables, updating values, destroying sessions, and building a simple login system.
Question 1: Start a Session Using session_start()
Problem Statement
Create a PHP program that starts a session and displays a welcome message.
PHP Solution
<?php
session_start();
echo "Welcome to PHP Sessions.";
?>
Sample Output
Welcome to PHP Sessions.
Explanation
session_start()starts a new session or resumes an existing session.- PHP uses a session identifier to recognize the user’s session.
- The welcome message is displayed after the session starts.
- Sessions must be started before sending output to the browser.
Concepts Covered
session_start()- Starting sessions
- PHP session basics
Question 2: Create and Store Session Variables
Problem Statement
Create a PHP program that stores a student’s name, age, and course in session variables.
PHP Solution
<?php
session_start();
$_SESSION["student_name"] = "Rahul";
$_SESSION["student_age"] = 20;
$_SESSION["student_course"] = "PHP";
echo "Student session data has been saved.";
?>
Sample Output
Student session data has been saved.
Explanation
$_SESSIONis a PHP superglobal array.- It stores information associated with the current session.
- Each session variable has a unique key.
- The stored values can be accessed on other pages belonging to the same session.
Concepts Covered
$_SESSION- Creating session variables
- Storing user information
Question 3: Access and Display Session Variables
Problem Statement
Create a PHP program that displays student information stored in session variables.
PHP Solution
<?php
session_start();
$_SESSION["student_name"] = "Amit";
$_SESSION["student_course"] = "Python";
echo "Student Name: " . $_SESSION["student_name"];
echo "\nCourse: " . $_SESSION["student_course"];
?>
Sample Output
Student Name: Amit
Course: Python
Explanation
session_start()resumes the current session.$_SESSION["student_name"]retrieves the student’s name.$_SESSION["student_course"]retrieves the course.- In a real application, these values can be created on one page and displayed on another.
Concepts Covered
- Accessing session variables
- Retrieving session data
- Session persistence
Question 4: Check Whether a Session Variable Exists
Problem Statement
Create a PHP program that checks whether a user is logged in by checking the existence of a session variable.
PHP Solution
<?php
session_start();
$_SESSION["username"] = "Rahul";
if (isset($_SESSION["username"])) {
echo "Welcome, " . $_SESSION["username"];
} else {
echo "User is not logged in.";
}
?>
Sample Output
Welcome, Rahul
Explanation
isset()checks whether a session variable exists and is notnull.- If the username exists, the welcome message is displayed.
- Otherwise, the program displays a message indicating that the user is not logged in.
Concepts Covered
isset()- Checking session variables
- Login status
Question 5: Update an Existing Session Variable
Problem Statement
Create a PHP program that updates an employee’s department stored in a session variable.
PHP Solution
<?php
session_start();
$_SESSION["employee_name"] = "Priya";
$_SESSION["department"] = "Sales";
echo "Old Department: " . $_SESSION["department"];
$_SESSION["department"] = "Marketing";
echo "\nUpdated Department: " . $_SESSION["department"];
?>
Sample Output
Old Department: Sales
Updated Department: Marketing
Explanation
- The employee’s original department is stored in a session variable.
- The program displays the original department.
- A new value is assigned to the same session key.
- The updated value replaces the previous value.
Concepts Covered
- Updating session variables
- Assigning session values
- Employee information management
Question 6: Remove a Specific Session Variable
Problem Statement
Create a PHP program that removes a student’s course information from the session while keeping the student’s name.
PHP Solution
<?php
session_start();
$_SESSION["student_name"] = "Amit";
$_SESSION["course"] = "PHP";
unset($_SESSION["course"]);
echo "Student Name: " . $_SESSION["student_name"];
if (isset($_SESSION["course"])) {
echo "\nCourse: " . $_SESSION["course"];
} else {
echo "\nCourse information has been removed.";
}
?>
Sample Output
Student Name: Amit
Course information has been removed.
Explanation
unset()removes a specific session variable.- The course information is removed.
- The student’s name remains available in the session.
- Removing one session variable does not destroy the entire session.
Concepts Covered
unset()- Removing session variables
- Managing session data
Question 7: Destroy a Session Using session_destroy()
Problem Statement
Create a PHP program that destroys the current session and logs the user out.
PHP Solution
<?php
session_start();
$_SESSION["username"] = "Rahul";
session_unset();
session_destroy();
echo "Session has been destroyed.";
?>
Sample Output
Session has been destroyed.
Explanation
session_start()starts or resumes the session.session_unset()removes all session variables.session_destroy()destroys the current session data on the server.- After destroying the session, the user must start a new session to store new session information.
Important: session_destroy() does not automatically remove the browser’s session cookie. A complete logout process should also expire the session cookie when one is being used.
Concepts Covered
session_unset()session_destroy()- Ending sessions
- Logout functionality
Question 8: Create a Session-Based Page Visit Counter
Problem Statement
Create a PHP program that counts how many times a user has visited a page during the current session.
PHP Solution
<?php
session_start();
if (isset($_SESSION["visit_count"])) {
$_SESSION["visit_count"]++;
} else {
$_SESSION["visit_count"] = 1;
}
echo "Page Visits: " . $_SESSION["visit_count"];
?>
Sample Output
First visit:
Page Visits: 1
Second visit:
Page Visits: 2
Third visit:
Page Visits: 3
Explanation
- The program checks whether
visit_countexists. - If it exists, the value increases by one.
- If it does not exist, the counter starts at 1.
- The updated value remains available throughout the session.
Concepts Covered
- Session-based counters
- Increment operators
- Session persistence
Question 9: Set and Check Session Data Across Two PHP Pages
Problem Statement
Create two PHP files. Store a user’s name on the first page and display it on the second page using sessions.
PHP Solution
File 1: set_session.php
<?php
session_start();
$_SESSION["username"] = "Rahul";
echo "User session has been created.";
echo '<br><a href="display_session.php">View User Details</a>';
?>
File 2: display_session.php
<?php
session_start();
if (isset($_SESSION["username"])) {
echo "Welcome, " . htmlspecialchars($_SESSION["username"]);
} else {
echo "Session data is not available.";
}
?>
Sample Output
First page:
User session has been created.
View User Details
Second page:
Welcome, Rahul
Explanation
set_session.phpstarts a session and stores the username.- The link opens
display_session.php. - The second page calls
session_start()to resume the same session. $_SESSION["username"]retrieves the saved name.htmlspecialchars()safely displays the username as text.
Concepts Covered
- Sharing session data between pages
- Multiple PHP files
- Session persistence
htmlspecialchars()
Question 10: Build a Simple Login and Logout System Using Sessions
Problem Statement
Create a simple PHP login system that checks a username and password, stores the username in a session after successful login, and provides a logout option.
PHP Solution
File 1: login.php
<?php
session_start();
$message = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$username = $_POST["username"];
$password = $_POST["password"];
if ($username === "admin" && $password === "12345") {
session_regenerate_id(true);
$_SESSION["username"] = $username;
header("Location: dashboard.php");
exit;
} else {
$message = "Invalid username or password.";
}
}
?>
<h2>Login Page</h2>
<form method="POST">
<label>Username:</label>
<input type="text" name="username" required>
<br><br>
<label>Password:</label>
<input type="password" name="password" required>
<br><br>
<button type="submit">Login</button>
</form>
<p><?php echo htmlspecialchars($message); ?></p>
File 2: dashboard.php
<?php
session_start();
if (!isset($_SESSION["username"])) {
header("Location: login.php");
exit;
}
?>
<h2>Welcome to Dashboard</h2>
<p>
Hello, <?php echo htmlspecialchars($_SESSION["username"]); ?>
</p>
<a href="logout.php">Logout</a>
File 3: logout.php
<?php
session_start();
$_SESSION = [];
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(
session_name(),
"",
time() - 3600,
$params["path"],
$params["domain"],
$params["secure"],
$params["httponly"]
);
}
session_destroy();
echo "You have been logged out.";
?>
Sample Output
Login Page:
Login Page
Username: admin
Password: 12345
Login
After successful login:
Welcome to Dashboard
Hello, admin
Logout
After clicking Logout:
You have been logged out.
Explanation
login.phpaccepts the username and password.- The program checks the entered credentials.
session_regenerate_id(true)creates a new session ID after successful authentication.$_SESSION["username"]stores the logged-in username.dashboard.phpchecks whether the user has an active login session.logout.phpclears the session data, expires the session cookie, and destroys the session.
Important: This is a learning example with hardcoded credentials. Real applications should use a database, password hashing with password_hash(), password verification with password_verify(), and appropriate security protections.
Concepts Covered
- Session-based login
- Session authentication
session_regenerate_id()- Page redirection
- Session destruction
- Logout functionality
Key Takeaways
- Sessions store user information on the server.
session_start()starts or resumes a session.$_SESSIONstores and retrieves session variables.isset()in PHP checks whether a session variable exists.unset()removes a specific session variable.session_unset()removes all session variables.session_destroy()destroys the current session data.session_regenerate_id()generates a new session ID.- Sessions are commonly used for login systems, dashboards, and shopping carts.
- Always protect session information and use HTTPS on live websites.
Frequently Asked Questions (FAQs)
1. What are sessions in PHP?
Sessions are used to store user information on the server so that it can be accessed across multiple pages during a user’s session.
2. Which function is used to start a session in PHP?
The session_start() function starts a new session or resumes an existing session.
3. What is $_SESSION in PHP?
$_SESSION is a PHP superglobal associative array used to store and access session variables.
4. What is the difference between cookies and sessions?
Cookies store information in the browser, while session data is generally stored on the server. PHP commonly uses a cookie containing a session ID to identify the user’s session.
5. How can we create a session variable in PHP?
You can create a session variable by assigning a value to $_SESSION, such as $_SESSION["username"] = "Rahul";.
6. How can we remove a session variable in PHP?
Use unset($_SESSION["username"]); to remove a specific session variable.
7. What is the difference between session_unset() and session_destroy()?
session_unset() removes all session variables, while session_destroy() destroys the current session data on the server.
8. How can we check whether a user is logged in using sessions?
You can check whether a login-related session variable exists using isset($_SESSION["username"]).
9. Where is PHP session data stored?
PHP session data is generally stored on the server. The storage location depends on the PHP session configuration.
10. Why should we use session_regenerate_id() after login?
It generates a new session ID, helping protect against session fixation attacks. It is good practice to regenerate the session ID after successful authentication.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
