Websites often need to remember information about a user as they move between different pages — whether that’s keeping them logged in, remembering items in a shopping cart, or storing their preferences. PHP Sessions and cookies make this kind of memory possible across multiple page visits.

This is Tutorial 10 of 10, the final tutorial in our PHP Basics for Beginners series. In this tutorial, you will learn how PHP Sessions work, how to use cookies, and how to combine both into a basic login-flow concept.

What are PHP Sessions?

PHP Sessions allow you to store data on the server that remains available across multiple pages during a single visit. Each visitor gets a unique session, identified by a session ID, which PHP tracks automatically behind the scenes using a cookie stored in the browser.

Without PHP Sessions, every page load would be treated as a completely fresh, disconnected request, with no memory of what happened on the previous page — including whether a user had logged in at all.

Starting a Session

Before you can use PHP Sessions on any page, you must call session_start() at the very beginning of your script, before any HTML output is sent to the browser.

<?php
session_start();

$_SESSION["username"] = "Ahmed";
echo "Session started and username saved.";
?>

Calling session_start() activates PHP Sessions for that page and makes the $_SESSION superglobal available for storing and retrieving values throughout the current visit.

Storing and Accessing Session Data

Once you start a session, you can store any value inside the $_SESSION array using a custom key, just like an associative array. That value then remains accessible on any other page during the same PHP Sessions lifecycle.

<?php
session_start();
$_SESSION["username"] = "Ahmed";
$_SESSION["role"] = "Student";
?>

On a different page, as long as session_start() runs first, you can retrieve those same values without needing to pass them through a URL or form again.

<?php
session_start();
echo "Welcome back, " . $_SESSION["username"];
echo "Role: " . $_SESSION["role"];
?>

Checking if a Session Variable Exists

Before accessing a session value, it is good practice to confirm it actually exists using isset(). This prevents warnings on pages where a user may not have logged in yet.

<?php
session_start();

if (isset($_SESSION["username"])) {
    echo "Hello, " . $_SESSION["username"];
} else {
    echo "You are not logged in.";
}
?>

Destroying a Session

When a user logs out, PHP Sessions need to end properly to clear their stored data. PHP provides two functions for this: session_unset() clears all session variables, and session_destroy() completely ends the session itself.

<?php
session_start();
session_unset();
session_destroy();

echo "You have been logged out.";
?>

Calling both functions together ensures no leftover data remains accessible after logout, which matters for both privacy and security in real applications.

What are Cookies?

Unlike PHP Sessions, which store data on the server, cookies store small pieces of data directly inside the user’s browser. Cookies can persist for a much longer period, even after the browser closes, depending on how they are configured.

Setting a Cookie

The setcookie() function creates a cookie, and it must be called before any HTML output is sent, similar to session_start().

<?php
setcookie("username", "Ahmed", time() + 3600, "/");
?>

This example creates a cookie named “username” with the value “Ahmed”, set to expire in one hour, and available across the entire site using the forward slash path.

Reading a Cookie

Once a cookie exists, you can access it on any page using the $_COOKIE superglobal, similar to how PHP Sessions use $_SESSION.

<?php
if (isset($_COOKIE["username"])) {
    echo "Welcome back, " . $_COOKIE["username"];
} else {
    echo "Cookie not found.";
}
?>

Sessions vs Cookies: Which to Use?

PHP Sessions are generally more secure since data stays on the server, making them the better choice for sensitive information like login status. Cookies work well for smaller, less sensitive data that needs to persist longer, such as remembering a user’s preferred language or theme. For complete technical documentation, refer to the official PHP sessions manual.

Basic Login-Flow Concept

Combining what you learned about PHP Forms in the previous tutorial with PHP Sessions here gives you the foundation of a login system. A form collects credentials, PHP checks them, and upon success, a session variable marks the user as logged in for every following page.

<?php
session_start();

if (isset($_POST["username"]) && $_POST["username"] == "admin") {
    $_SESSION["loggedIn"] = true;
    echo "Login successful!";
} else {
    echo "Invalid username.";
}
?>

<form action="" method="POST">
    Username: <input type="text" name="username">
    <input type="submit" value="Login">
</form>

This simplified example demonstrates the core idea behind every login system you will encounter, though real applications add password hashing and database checks, which fall outside the scope of this beginner series.

Congratulations — Series Complete!

You have now completed all ten tutorials in the PHP Basics for Beginners series, covering everything from PHP Installation and variables to functions, arrays, forms, and PHP Sessions. You have built a solid foundation to continue toward more advanced PHP topics like object-oriented programming and database integration.

If you missed the previous lesson, check out Tutorial 9: PHP Forms Guide, or explore all lessons in our PHP category.

Practice Exercise

Complete the following tasks to reinforce what you learned in this tutorial:

  • Create a PHP file named sessions-practice.php
  • Start a session and store your name and favorite hobby inside $_SESSION
  • Create a second file that starts a session and displays both stored values
  • Add an isset() check before displaying session data, with a fallback message if it is missing
  • Create a logout script that uses session_unset() and session_destroy() together
  • Set a cookie storing a user’s preferred theme (light or dark) that expires in 24 hours
  • Read the cookie value on a separate page and display an appropriate message based on its value

Bonus Challenge: Build a simple login-flow script combining a PHP Forms login page with PHP Sessions, where a correct username and password combination sets a session variable, and an incorrect one displays an error message without setting the session.

About Author

Arshad Sultan

Arshad Sultan is the Founder of Tutorials Ocean and a Technical Architect & Full-Stack Developer with 15+ years of experience in PHP, Laravel, CRM development, API integrations, and AI-powered automation. He also runs Rapid Code, a software and AI automation agency, and has trained hundreds of students across Karachi's IT institutes since 2010.

Leave a Reply

Your email address will not be published. Required fields are marked *