Session
Index
Purpose
- Assists in maintaining state for web requests (HTTP).
Process and Principle
Setting up Session
Install Dependencies
composer require hyperf/session
Publish Configuration
php bin/hyperf.php vendor:publish hyperf/session
<?php
declare(strict_types=1);
use Hyperf\Session\Handler;
return [
'handler' => Handler\FileHandler::class, // ้ฉฑๅจ็ฑปๅ
'options' => [
'connection' => 'default',
'path' => BASE_PATH . '/runtime/session',
'gc_maxlifetime' => 1200,
'session_name' => 'HYPERF_SESSION_ID',
'domain' => null,
'cookie_lifetime' => 5 * 60 * 60,
'cookie_same_site' => 'lax',
],
];
Add Middleware
config/autoload/middlewares.php
<?php
declare(strict_types=1);
return [
'http' => [
...
// Sessionไธญ้ดไปถ(ๅฎๆน)
Hyperf\Session\Middleware\SessionMiddleware::class,
...
],
];
Example Usage
#[GetMapping(path: 'session/set')]
public function setSession(): array
{
$this->session->set('ttt', 'xxx');
return $this->result->getResult();
}
#[GetMapping(path: 'session/get')]
public function getSession(): array
{
$session = $this->session->all();
return $this->result->setData($session)->getResult();
}
Considerations
- Session relies on the Cookie mechanism. If cookies are disabled, Session will not work properly (Session uses cookies as a medium to transmit the SESSION_ID).
- Each request will set a
set-cookie
header, but the SESSION_ID for the same session will not change. - For clustered services using load balancing, Sessions should be centrally stored to prevent issues with duplicate session creation and session loss.
- Cross-origin issues can also arise. Refer to Cross-origin
ใWarningใ
Sessions and JWT (tokens) essentially issue an identifier, and the client carries the identifier for validation. However, the focus is different:
Session stores the identifier and checks whether the identifier is stored and retrieves stored data.
Token uses algorithmic validation and is generally not stored; if validation passes, it is considered a legitimate request.
Time and Space are the trade-off issues.