All posts
PHPOctober 12, 20267 min read

PHP Sessions Explained for Beginners (With Examples)

What is a PHP session? Learn how to start, use and destroy sessions step by step, with simple copy-paste examples and a basic login demo for beginners.

F
Fepiq Team
Fepiq

What is a PHP session, and how do you use one? A PHP session is a way to remember information about a visitor, such as their name or whether they are logged in, while they move from page to page. In this beginner guide you will learn how to start a session, save data, read it back and end it, using small examples you can copy and run.

Why do we need sessions?

Web pages have no memory. Each time a browser asks for a page, the server treats it as a brand new visit. If you type your name on page one, page two has already forgotten it.

A session fixes this. PHP gives each visitor a unique ID and stores their data on the server. The browser keeps only the ID, inside a small file called a cookie (a tiny piece of text saved by the browser). On every request the browser sends the ID back, and PHP finds the matching data.

What you need before you start

  • PHP installed on your computer (version 8 or newer is best).
  • A text editor and a folder for your files.
  • Basic PHP knowledge: variables and echo.

To run the examples, open a terminal in your folder and start PHP's built-in web server. Then visit http://localhost:8000/ and the file name in your browser.

bash
php -S localhost:8000

Step 1: Start a session

Every page that uses sessions must call session_start() before any output. Output means any text or HTML sent to the browser, even a blank line before the opening PHP tag.

php
<?php
session_start();

$_SESSION['username'] = 'Maria';
echo 'Session saved!';

Line 2 starts the session or continues the one the visitor already has. Line 4 stores the text Maria inside $_SESSION, a special array (a list of named values) that PHP keeps for each visitor. Line 5 prints a message. Save this as set.php.

Step 2: Read session data on another page

Now make a second file called hello.php. It starts the session again and reads the value saved earlier.

php
<?php
session_start();

if (isset($_SESSION['username'])) {
    echo 'Hello, ' . $_SESSION['username'] . '!';
} else {
    echo 'I do not know you yet.';
}

session_start() on line 2 reconnects to the visitor's data. The isset() function on line 4 checks that the key exists, which avoids errors. If it exists, line 5 prints a greeting. Visit set.php first, then hello.php, and you will see Hello, Maria!

Step 3: Change and remove session data

Because $_SESSION is an array, you change it like any array. Use unset() to delete one value.

php
<?php
session_start();

$_SESSION['visits'] = ($_SESSION['visits'] ?? 0) + 1;
echo 'You have visited ' . $_SESSION['visits'] . ' times.';

unset($_SESSION['username']);

Line 4 uses ?? (the null coalescing operator), which means: use the left value if it exists, otherwise use 0. Then it adds 1. Each refresh raises the counter. Line 7 removes only the username and keeps the rest.

Step 4: Destroy a session (log out)

To end a session completely, clear the array and destroy the session. This is what a logout page does.

php
<?php
session_start();

$_SESSION = [];
session_destroy();

echo 'You are logged out.';

Line 4 empties all the data. Line 5 deletes the session on the server. Always start the session first, otherwise there is nothing to destroy.

Step 5: A simple login example

Sessions are most often used for logins. Here is a tiny version with a fixed password. Real sites check a database and store hashed passwords with password_hash() and password_verify().

php
<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user = $_POST['user'] ?? '';
    $pass = $_POST['pass'] ?? '';

    if ($user === 'admin' && $pass === 'secret') {
        session_regenerate_id(true);
        $_SESSION['logged_in'] = true;
        echo 'Welcome back!';
    } else {
        echo 'Wrong details.';
    }
}
?>
<form method="post">
  <input name="user" placeholder="User">
  <input name="pass" type="password" placeholder="Password">
  <button>Log in</button>
</form>

Line 4 checks that the form was sent. Lines 5 and 6 read what the visitor typed. Line 8 compares it to the expected values. Line 9 creates a fresh session ID, which protects against session fixation, an attack where someone tricks you into using an ID they already know. Line 10 marks the visitor as logged in. Other pages can check $_SESSION['logged_in'] before showing private content.

Sessions vs cookies

FeatureSessionCookie
Where data livesOn the serverIn the browser
Safe for private dataYes, mostlyNo, the user can edit it
Size limitLargeAbout 4 KB
Lasts untilBrowser closes, or a timeoutA date you choose

Common mistakes and tips

  • Output before session_start() gives a headers already sent warning. Put it at the very top.
  • Forgetting session_start() on a page means $_SESSION is empty there.
  • Never store passwords in a session.
  • Use HTTPS on real websites so session IDs cannot be stolen.
  • Call session_regenerate_id(true) right after login.

Sessions work best with forms. If you have not yet learned how PHP receives form data, read this first.

Read: PHP Form Handling (GET vs POST)

Frequently asked questions

What is a session in PHP?+

A session is a way to store information about a visitor on the server so it is available across many pages. PHP gives the visitor a unique ID, kept in a cookie, to find that data again. The data is held in the $_SESSION array.

Where does PHP store session data?+

By default PHP saves each session as a small file in a temporary folder on the server. Only the session ID is sent to the browser. Larger sites sometimes keep sessions in a database instead.

What is the difference between a session and a cookie?+

A cookie is stored in the visitor's browser and can be changed by them. A session keeps the real data on the server and uses just a cookie for the ID. Use sessions for anything private, such as login status.

Why do I get the error headers already sent?+

This happens when something was printed before session_start(), even a space or blank line before the opening PHP tag. Move session_start() to the very first line of the file.

How long does a PHP session last?+

By default it ends when the browser closes, and the server may also delete idle sessions after about 24 minutes. You can change this in your PHP settings or cookie options.

Want help building a login system or a complete website? Our team is happy to talk.

Talk to Fepiq

Get new posts in your inbox

Occasional, no-fluff notes on shipping modern software — startups, automation, Laravel, Shopify and more. No spam, unsubscribe anytime.

Keep reading

Related posts

All posts

Let's build something

Ready to ship your next product with Fepiq?

Book a free discovery call. We'll listen, ask sharp questions, and send you a proposal within 3 business days.