Documentation Tools
Sessions
Working with sessions: standard PHP sessions or storage in the database.
Basics
The olala\modules\Session module gives you a single interface to the session. By default it works on top of standard
PHP sessions ($_SESSION). The set() and get() methods start the session themselves,
while add() and destroy() require it to be already started.
use olala\modules\Session;
Session::set('user_id', 42);
Session::get('user_id'); // 42
Session::get('cart', []); // default value
Session::add('viewed', 15); // append an element to an array
Session::add('viewed', 16); // ['viewed' => [15, 16]]
Session::destroy(); // end the sessionYou can start the session explicitly from a controller: $this->startSession() or Session::start().
Example: login and logout
<?php
use olala\controller;
use olala\modules\Session;
use site\models\User;
class AuthIndexController extends controller {
// POST /auth/index/login
function loginAction() {
$user = User::check($_POST['email'] ?? '', $_POST['password'] ?? '');
if (!$user)
return $this->render('login', ['error' => 'Wrong email or password']);
Session::set('user_id', $user['id']);
header('Location: /account');
return '';
}
// /auth/index/logout
function logoutAction() {
Session::start();
Session::destroy();
header('Location: /');
return '';
}
}Sessions in the database
For APIs and mobile apps, where cookies are inconvenient, there's a second mode: session data is stored
in the cache and in the site.sessions table. Enable it in config.php:
use olala\modules\Session;
Session::$engine = 'db'; // any value other than 'php'The session ID is looked up in this order:
- in the
sidrequest header; - in the
?sid=…URL parameter; - in the
msidcookie.
If there's no ID, a new one is created and saved in the msid cookie for 90 days.
Every set() and add() immediately writes the data to the cache and the database, and the user_id value
is duplicated into a separate column — handy for finding a user's sessions.
fetch('/api/profile', { headers: { sid: localStorage.sid } });This mode requires a configured database, the site.sessions table (columns id, sid, ip, data, ping, user_id) and a cache/ folder.
Methods
| Method | What it does |
|---|---|
Session::start() | starts the session (a repeated call does nothing) |
Session::set($key, $value) | stores a value |
Session::get($key, $default) | reads a value |
Session::add($key, $value) | appends an element to the array under the key |
Session::destroy() | destroys the session |
Session::gen($ip) | DB mode: creates a new session and returns its sid |
Session::$sid | DB mode: the current ID |