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.
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.
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.
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.
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.
php -S localhost:8000Every 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
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.
Now make a second file called hello.php. It starts the session again and reads the value saved earlier.
<?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!
Because $_SESSION is an array, you change it like any array. Use unset() to delete one value.
<?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.
To end a session completely, clear the array and destroy the session. This is what a logout page does.
<?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.
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
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.
| Feature | Session | Cookie |
|---|---|---|
| Where data lives | On the server | In the browser |
| Safe for private data | Yes, mostly | No, the user can edit it |
| Size limit | Large | About 4 KB |
| Lasts until | Browser closes, or a timeout | A date you choose |
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)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.
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.
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.
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.
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 FepiqOccasional, no-fluff notes on shipping modern software — startups, automation, Laravel, Shopify and more. No spam, unsubscribe anytime.
Keep reading
Learn SQL CASE WHEN step by step. This beginner guide shows how to label, group and sort data with simple examples you can copy and run today.
PostgreSQL ILIKE explained for beginners: search text without worrying about case, learn % and _ wildcards, and copy simple examples you can run today.
Let's build something
Book a free discovery call. We'll listen, ask sharp questions, and send you a proposal within 3 business days.