Hello! Welcome back to our module on Session Management and User Authentication.
In the previous lesson, we established the fundamental difference between cookies and sessions. We learned that while cookies store data on the client's browser, sessions store data securely on the server, using a cookie only to hold a unique session ID. This makes sessions the ideal choice for sensitive information like user login status.
Today, we move from the "what" to the "how." This lesson will guide you through the practical steps of using PHP's session management system. Our goal is to master the ability to start and manage user sessions, storing and retrieving data from the $_SESSION superglobal. This is a core skill for building almost any dynamic web application, from e-commerce sites with shopping carts to forums with logged-in members.
The Session Lifecycle: A High-Level View
Before we dive into the code, let's visualize the entire process. Remember the coat-check analogy? The server stores your belongings (session data) and gives you a ticket (session ID). This diagram illustrates that client-server interaction.

Our lesson today will focus on the PHP functions that make steps 2, 3, and 6 happen.
1. Starting a Session with session_start()
The first and most important function is session_start(). You must call this function at the beginning of any PHP script that needs to access session data.
When you call session_start(), PHP performs one of two actions:
- If the user's browser sends a valid session ID cookie (usually named
PHPSESSID), PHP finds the corresponding session data file on the server and loads its contents into the$_SESSIONsuperglobal array. - If no session ID is found, PHP creates a new, unique session ID, prepares to send it to the browser as a cookie, and initializes an empty
$_SESSIONarray.
Let's see this in action. The following video demonstrates how calling session_start() generates the PHPSESSID cookie, which you can see in your browser's developer tools.
25 | How to Create Sessions in PHP for Beginners | 2023 | Learn PHP Full Course For Beginners
Watch this clip from Dani Krossing to see a practical demonstration of starting a session and observing the resulting PHPSESSID cookie in the browser.
Watch from 03:19 to 05:33. Pay close attention to how he uses the browser's developer tools (Storage > Cookies) to show the PHPSESSID cookie appearing after the page with session_start() is loaded.
2. A Critical Rule: Headers and session_start()
There is one golden rule you must always remember: session_start() must be called before any output is sent to the browser.
Output includes:
- HTML tags (even a single space or doctype declaration before
<?php) echoorprintstatements- Whitespace outside of
<?php ... ?>tags in included files.
Why? Because session_start() needs to send the Set-Cookie HTTP header to the browser. Headers can only be sent before the main body of the response begins. If you try to call session_start() after even a single byte of content has been sent, PHP will issue a "Warning: session_start(): Cannot start session when headers already sent" error. This is a very common stumbling block for new PHP developers.
The following video provides an excellent, in-depth explanation of this issue and the related concept of output buffering. Understanding this will save you hours of debugging in the future.
PHP Sessions & Cookies - Output Buffering - Headers Already Sent Warning - Full PHP 8 Tutorial
This clip from Program With Gio explains the 'headers already sent' warning in detail, why it happens, and how PHP's configuration (output buffering) can sometimes mask the issue. This is crucial knowledge for professional development.
Watch from 00:36 to 06:10. Focus on the cause of the error and the key takeaway: to avoid any potential issues, always place session_start() at the very top of your script before any other code or HTML.
Best Practice: To be safe, always place session_start() at the absolute top of your PHP files.
<?php
session_start(); // This should be the very first thing.
// The rest of your PHP code...
?>
<!DOCTYPE html>
<html>
<!-- Your HTML... -->
</html>
3. Storing and Accessing Data with $_SESSION
Once a session is started, you can store and retrieve data using the $_SESSION superglobal array. It's a standard PHP associative array, so working with it is straightforward.
- To store data:
$_SESSION['key'] = 'value'; - To retrieve data:
$variable = $_SESSION['key'];
The beauty of this is that any data you store in $_SESSION on one page will be available on any other page within your application, as long as you call session_start() on that page too.
This next video segment demonstrates this cross-page data persistence.
25 | How to Create Sessions in PHP for Beginners | 2023 | Learn PHP Full Course For Beginners
Let's return to Dani Krossing's video to see how to add data to the $_SESSION array and then access it from a completely different page.
Watch from 05:33 to 07:44. Notice how he sets a $_SESSION['username'] on one page and is able to echo it out on another page (example.php) simply by starting the session there.
Here is a simple, self-contained example:
page1.php
<?php
// Start the session
session_start();
// Store user information
$_SESSION['username'] = 'Alex';
$_SESSION['user_id'] = 123;
echo 'Hello, ' . $_SESSION['username'] . '. Your session is set.';
echo '<br><a href="page2.php">Go to Page 2</a>';
?>
page2.php
<?php
// Resume the session
session_start();
// Check if the user data exists before using it
if (isset($_SESSION['username'])) {
echo 'Welcome back, ' . $_SESSION['username'] . '!';
echo '<br>Your user ID is: ' . $_SESSION['user_id'];
echo '<br><a href="logout.php">Logout</a>';
} else {
echo 'You are not logged in.';
echo '<br><a href="page1.php">Login</a>';
}
?>
Using isset() is important to avoid errors if you try to access a session variable that hasn't been set (e.g., if a user visits page2.php directly without "logging in" on page1.php).
4. Modifying and Ending a Session
Managing a session also involves changing and removing data.
Removing a Single Item
To remove a specific variable from the session, use the unset() function, just as you would with any array element.
// Removes the 'username' key and its value from the session
unset($_SESSION['username']);
Destroying the Entire Session
When a user logs out, you need to completely end their session. This is a two-step process for best results:
session_unset(): This function clears all data from the$_SESSIONarray.session_destroy(): This function destroys all of the data associated with the current session on the server. It removes the session file itself.
The following video covers unset(), session_unset(), and session_destroy(), and highlights a very important quirk about how session_destroy() works.
25 | How to Create Sessions in PHP for Beginners | 2023 | Learn PHP Full Course For Beginners
This final clip demonstrates how to remove specific session variables and how to completely terminate a session, which is essential for building a logout feature.
Watch from 07:44 to 11:14. Pay special attention to the explanation that the effects of session_destroy() are not seen until the user navigates to a new page. This is a common point of confusion.
Here's how you would typically implement a logout.php file:
logout.php
<?php
session_start(); // Resume the session
// 1. Unset all session variables
$_SESSION = []; // A more robust way than session_unset()
// 2. Destroy the session cookie (optional but good practice)
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// 3. Finally, destroy the session on the server
session_destroy();
// Redirect to a public page
header('Location: page1.php');
exit;
?>
Note: The code to delete the cookie is more advanced and we will cover cookies in detail in the next lesson. The crucial part for now is session_destroy().
Finally, a quick but important warning from the official PHP manual: do not use unset($_SESSION). This will break the $_SESSION superglobal and you will no longer be able to store data in it. Always unset individual keys or clear the array with $_SESSION = [];.
Conclusion
You now have the practical tools to manage user state in PHP. By combining session_start() with the $_SESSION superglobal, you can create seamless, multi-page experiences for your users, from remembering their login status to managing a shopping cart.
Key Takeaways:
- Always call
session_start()at the very top of any script that needs session access. - Be vigilant about the "headers already sent" error; it means you have output before
session_start(). - Store and retrieve data using the
$_SESSIONassociative array (e.g.,$_SESSION['user_id'] = 123;). - Always check for session data with
isset()before using it to prevent errors. - Use
unset($_SESSION['key'])to remove a specific item. - Use
session_destroy()to end a session completely, typically during a logout process.
Preview of the Next Lesson:
We've seen that PHP sessions use a cookie behind the scenes to store the session ID. But what if we want to manage cookies directly? In the next lesson, we will learn how to set, read, and delete cookies using PHP functions. This will enable us to implement features like a "Remember Me" checkbox on a login form.