Sessions and flash data
A site does not remember a visitor between requests: every page is requested anew. A session solves this — it is a data store tied to one visitor: a cart, the chosen language, the logged-in flag. No files need to be created for it: you work with the session through the session() function in controllers and views.
Writing and reading
// app/Controllers/Home.php
public function index(): string
{
$visits = (session()->get('visits') ?? 0) + 1;
session()->set('visits', $visits);
return "You have opened this page $visits times";
}Reload the home page several times and the number grows. Open the site in another browser and the count starts from one: every visitor has a session of their own. The session() function starts the session on first use.
Session methods
| Call | What it does |
|---|---|
session()->set('name', 'Anna') | Writes a value |
session()->get('name') | Reads a value or returns null |
session('name') | The short form of reading |
session()->has('name') | Checks whether the value exists |
session()->remove('name') | Removes a value |
session()->destroy() | Removes the whole session |
A message for one request
Flash data are values that live exactly until the next request. They carry messages like "Post saved" across a redirect:
// app/Controllers/Posts.php
public function create()
{
// validating and saving the post
return redirect()->to('/posts')->with('message', 'Post saved');
}The with() method writes a flash value. The call session()->setFlashdata('message', 'Post saved') does the same.
Showing the message
The message is best output in the layout so that it works on every page:
<!-- app/Views/layouts/main.php, inside the main tag -->
<?php if (session()->getFlashdata('message')): ?>
<p class="flash"><?= esc(session()->getFlashdata('message')) ?></p>
<?php endif ?>After a post is saved, "Post saved" appears above the list. Reload the page and the message is gone.
Where sessions are stored
The settings live in app/Config/Session.php. By default the data is stored in files in the writable/session folder, and only a cookie with the session identifier is sent to the visitor's browser.
| Property | What it sets |
|---|---|
$driver | The storage: files, database, Redis |
$expiration | The session lifetime in seconds, 7200 by default |
$savePath | The folder or table used for storage |
$cookieName | The name of the identifier cookie |
The storage is switched to a database or Redis when the site runs on several servers.
Common mistake
A session is no place for large data. If you put a list of posts or a whole user object into it, the data goes stale: the record in the database changes while the session keeps the old copy. Store only identifiers and small settings in the session — user_id, for example — and read the data itself from the database on every request.