Kotchasan Framework Documentation
Session Class - Database Session Management
Session Class - Database Session Management
The Session class handles session management by storing session data in a database table (Database Session Handler) instead of the file system. It also provides helper methods for reading and writing to $_SESSION.
Namespace
Kotchasan\SessionFeatures
Designed to work with PHP's session_set_save_handler(), this class redirects session storage to the sessions database table, offering benefits such as:
- Support for Load Balancing environments (multiple servers sharing a DB).
- Enhanced security and manageability compared to file-based sessions.
- Ability to track online users easily.
Public Methods
createTable()
Create the database table for storing sessions (typically termed during installation).
public function createTable(): boolReturns: true on success.
session()
Get a value from Session ($_SESSION)
public function session(string $name, mixed $default = null): mixedParameters:
$name- Session key$default- Default value if key is not found (Default: null)
Returns: Stored value or $default
Example:
$user_id = $session->session('user_id', 0);setSession()
Set a value to Session ($_SESSION)
public function setSession(string $name, mixed $value): selfParameters:
$name- Session key$value- Value to store
Returns: Self instance (Chainable)
Example:
$session->setSession('user_id', 123)
->setSession('role', 'admin');Internal Methods (Session Handler)
These methods are used automatically by PHP's Session Manager and should rarely be called directly:
_open(): Opens database connection._close(): Closes session operation._read($sess_id): Reads session data from DB._write($sess_id, $data): Writes/Updates session data to DB._destroy($sess_id): Deletes a session by ID._gc($max): Garbage collection for expired sessions.
Setup & Usage
Typically, the framework initializes this automatically if Database Session is configured.
$sess = new \Kotchasan\Session;
session_set_save_handler(
[$sess, '_open'],
[$sess, '_close'],
[$sess, '_read'],
[$sess, '_write'],
[$sess, '_destroy'],
[$sess, '_gc']
);
register_shutdown_function('session_write_close');
session_start();File Size: 184 lines