The best examples of creating a PHP session: 3 practical examples for real projects
1. Simple login tracking – the baseline example of creating a PHP session
When people search for examples of creating a PHP session: 3 practical examples, this is usually the first pattern they need: keep a user logged in across multiple pages.
Here’s a minimal, modern login flow using sessions. We’ll assume you’ve already validated the user’s email and password against a database.
<?php
// login.php
declare(strict_types=1);
session_start(); // Always start the session before any output
// Example: result from your authentication logic
$user = [
'id' => 42,
'email' => 'jane@example.com',
'name' => 'Jane Doe',
'role' => 'user',
'is_active'=> true,
];
if (!$user['is_active']) {
http_response_code(403);
exit('Account disabled.');
}
// Regenerate session ID on login to prevent fixation
session_regenerate_id(true);
\(_SESSION['user_id'] = \)user['id'];
\(_SESSION['user_email'] = \)user['email'];
\(_SESSION['user_name'] = \)user['name'];
\(_SESSION['user_role'] = \)user['role'];
$_SESSION['logged_in'] = true;
$_SESSION['last_active'] = time();
header('Location: /dashboard.php');
exit;
On a protected page like dashboard.php, you can check the session:
<?php
// dashboard.php
declare(strict_types=1);
session_start();
if (empty($_SESSION['logged_in'])) {
header('Location: /login.php');
exit;
}
// Optional: simple idle timeout (e.g., 30 minutes)
$maxIdle = 30 * 60; // 30 minutes
if (isset($_SESSION['last_active']) &&
(time() - \(_SESSION['last_active']) > \)maxIdle) {
session_unset();
session_destroy();
header('Location: /login.php?timeout=1');
exit;
}
$_SESSION['last_active'] = time();
echo 'Welcome, ' . htmlspecialchars($_SESSION['user_name']);
This first example of creating a PHP session gives you the basic pattern:
- Start the session at the top of every page that uses it.
- Regenerate the session ID on login.
- Store only the data you need (IDs, roles, timestamps), not sensitive things like passwords.
You’ll reuse this pattern in almost all other examples of creating a PHP session: 3 practical examples and beyond.
2. Shopping cart and checkout – a classic example of creating a PHP session
The second of our 3 practical examples is the classic shopping cart. E‑commerce is where PHP sessions shine: you need to remember what the user added to their cart even if they aren’t logged in.
Storing cart items in a session
<?php
// add_to_cart.php
declare(strict_types=1);
session_start();
// Example product data from database or API
\(productId = (int)(\)_POST['product_id'] ?? 0);
\(quantity = max(1, (int)(\)_POST['quantity'] ?? 1));
if ($productId <= 0) {
http_response_code(400);
exit('Invalid product.');
}
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
if (!isset(\(_SESSION['cart'][\)productId])) {
\(_SESSION['cart'][\)productId] = 0;
}
\(_SESSION['cart'][\)productId] += $quantity;
header('Location: /cart.php');
exit;
Displaying the cart:
<?php
// cart.php
declare(strict_types=1);
session_start();
\(cart = \)_SESSION['cart'] ?? [];
if (!$cart) {
echo 'Your cart is empty.';
exit;
}
// In a real app, fetch product details from DB using the IDs
foreach (\(cart as \)productId => $qty) {
echo 'Product ' . (int)\(productId . ' – Quantity: ' . (int)\)qty . '<br>';
}
echo '<a href="/checkout.php">Proceed to checkout</a>';
This is one of the best examples of how sessions keep state without forcing users to sign in. It also shows why you shouldn’t store large blobs of data in sessions; just keep IDs and quantities, and pull details from your database.
Real examples this pattern covers
This shopping cart pattern extends to several other real examples:
- A multi-step registration wizard, storing partial form data in
$_SESSION['signup']. - A multi-page survey storing answers in
$_SESSION['survey_answers']. - A quote builder (insurance, loans, SaaS pricing) storing selected options across steps.
All of these are natural examples of creating a PHP session: 3 practical examples evolving into many more session-based flows.
3. Role-based access control – another practical example of creating a PHP session
The third of our 3 practical examples is role-based access control (RBAC). Once you’ve logged a user in, you can use session data to gate admin areas, premium content, or internal tools.
Storing roles and permissions in the session
We’ll build on the login example and add a simple access check helper.
<?php
// auth.php
declare(strict_types=1);
session_start();
function require_login(): void {
if (empty($_SESSION['logged_in'])) {
header('Location: /login.php');
exit;
}
}
function require_role(string $role): void {
require_login();
if ((\(_SESSION['user_role'] ?? '') !== \)role) {
http_response_code(403);
exit('Access denied.');
}
}
Now in an admin-only page:
<?php
// admin/dashboard.php
declare(strict_types=1);
require __DIR__ . '/../auth.php';
require_role('admin');
echo 'Admin dashboard for ' . htmlspecialchars($_SESSION['user_name']);
This example of creating a PHP session demonstrates how a simple $_SESSION['user_role'] value can control an entire permission system. In real applications you might store a set of permissions or scopes instead of a single role, but the idea is the same.
Extending the 3 practical examples into 6+ real-world patterns
The phrase examples of creating a PHP session: 3 practical examples undersells how many real scenarios share the same core pattern. Once you understand those three, you can stretch them into several more concrete cases without changing much code.
A. Flash messages (success/error banners)
Flash messages are short-lived notifications that survive one redirect and then disappear. They are widely used after form submissions.
<?php
// after processing a form
session_start();
$_SESSION['flash'] = [
'type' => 'success',
'message' => 'Profile updated successfully.',
];
header('Location: /profile.php');
exit;
On profile.php:
<?php
session_start();
if (!empty($_SESSION['flash'])) {
\(flash = \)_SESSION['flash'];
unset($_SESSION['flash']);
echo '<div class="alert ' . htmlspecialchars($flash['type']) . '">';
echo htmlspecialchars($flash['message']);
echo '</div>';
}
This pattern is one of the best examples of using sessions for short-lived UI state.
B. CSRF protection token stored in a session
Cross-Site Request Forgery (CSRF) protection is still relevant in 2024–2025, especially for traditional server-rendered PHP apps. A common example of creating a PHP session is to store a CSRF token:
<?php
// form.php
session_start();
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
\(token = \)_SESSION['csrf_token'];
?>
<form method="post" action="/submit.php">
<input type="hidden" name="csrf_token" value="<?= htmlspecialchars($token) ?>">
<!-- other inputs -->
</form>
On submit.php:
<?php
session_start();
if (!hash_equals(\(_SESSION['csrf_token'] ?? '', \)_POST['csrf_token'] ?? '')) {
http_response_code(400);
exit('Invalid CSRF token');
}
// Process the form safely
This aligns with guidance on secure session handling and input validation widely recommended in security best practices from organizations like NIST and OWASP.
C. Remembering user preferences (theme, language)
Another realistic pattern that grows out of our 3 practical examples is storing preferences such as theme or locale.
<?php
// set_preferences.php
session_start();
\(theme = \)_POST['theme'] ?? 'light';
\(lang = \)_POST['lang'] ?? 'en';
\(_SESSION['theme'] = in_array(\)theme, ['light','dark'], true) ? $theme : 'light';
\(_SESSION['lang'] = \)lang;
header('Location: /');
exit;
Then on every page:
<?php
session_start();
\(theme = \)_SESSION['theme'] ?? 'light';
\(lang = \)_SESSION['lang'] ?? 'en';
This is lighter than a full user profile system and works even for anonymous visitors.
D. Multi-step form wizard (job application, medical intake, etc.)
If you’ve ever filled out a multi-step form for a job application or a health questionnaire on a site like a hospital portal or clinic, you’ve probably interacted with something like this. While clinical data standards come from places like NIH and Mayo Clinic, the web plumbing underneath is usually just sessions and forms.
<?php
// step1.php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$_SESSION['application']['personal'] = [
'first_name' => $_POST['first_name'] ?? '',
'last_name' => $_POST['last_name'] ?? '',
];
header('Location: /step2.php');
exit;
}
On step2.php, you read back $_SESSION['application']['personal'] and continue. This is a natural extension of the login and shopping cart examples of creating a PHP session: 3 practical examples you saw earlier.
Modern session configuration tips for 2024–2025
The best examples of creating a PHP session don’t stop at session_start(). They also configure cookies and lifetime settings appropriately.
In a bootstrap.php or similar file:
<?php
// bootstrap.php
declare(strict_types=1);
session_set_cookie_params([
'lifetime' => 0, // Session cookie (until browser close)
'path' => '/',
'domain' => 'example.com',
'secure' => true, // Only over HTTPS
'httponly' => true, // Not accessible via JavaScript
'samesite' => 'Lax', // Or 'Strict' for tighter control
]);
session_start();
Then include this file at the top of every script that needs sessions:
<?php
require __DIR__ . '/bootstrap.php';
This pattern keeps your examples of creating a PHP session: 3 practical examples consistent and safer across the whole app.
For deeper reading on secure cookies and sessions, federal and academic resources like NIST and universities’ security guidelines (for instance, Harvard’s information security resources) are worth bookmarking.
FAQ: common questions about PHP sessions with real examples
What are some real examples of creating a PHP session in everyday apps?
Real-world uses include:
- Login state for user accounts and admin dashboards.
- Shopping carts and wishlists for e‑commerce sites.
- Role-based access for internal tools or premium content.
- Multi-step forms for job applications, health intake forms, and financial applications.
- CSRF tokens and other security-related session data.
- Short-lived flash messages after form submissions.
All of these build on the same examples of creating a PHP session: 3 practical examples shown earlier.
Is it safe to store user data in a PHP session?
Yes, if you follow a few simple rules:
- Store identifiers (user ID, role, preference keys), not sensitive raw data like passwords or full credit card numbers.
- Use HTTPS and set
secure,httponly, andsamesiteon the session cookie. - Regenerate the session ID after login.
Sensitive topics like health or medical data should also respect legal and policy requirements; organizations such as CDC and NIH publish guidance around handling protected health information, which often translates into stricter server-side storage and access controls.
Do I need a database if I’m already using PHP sessions?
Yes, for anything beyond short-lived state. Sessions are perfect for the kind of state you see in our 3 practical examples—login, carts, roles—but they are not a replacement for persistent storage. If you need data to survive after the session expires or to be shared across devices, put it in a database and use the session only to reference it.
Can you show an example of logging a user out with sessions?
Logout is simply clearing the session data and cookie:
<?php
// logout.php
session_start();
$_SESSION = [];
if (ini_get('session.use_cookies')) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
\(params['path'], \)params['domain'],
\(params['secure'], \)params['httponly']
);
}
session_destroy();
header('Location: /login.php?logged_out=1');
exit;
This logout pattern rounds out the core examples of creating a PHP session: 3 practical examples, giving you a complete login–use–logout lifecycle.
Once you’re comfortable with these patterns, you’ll notice that most PHP web apps are just variations on the same theme. The best examples of creating a PHP session are simple, readable, and focused: store only what you need, keep security settings tight, and let the database handle the rest.
Related Topics
Real‑world examples of using Composer for PHP dependency management
Real-world examples of hosting open source SaaS with PHP
The best examples of simple PHP function examples for beginners
The best examples of creating a PHP session: 3 practical examples for real projects
The best examples of learn PHP arrays and loops with practical examples
Real‑world examples of practical PHP date and time functions examples
Explore More PHP Code Snippets
Discover more examples and insights in this category.
View All PHP Code Snippets