Cookie & LocalStorage Management
Rhapsody provides a secure, modern API for managing browser cookies and localStorage directly from your PHP controllers and Twig templates. Both systems are designed with security and ease of use in mind, leveraging PHP 8.4 features like enums and typed properties.
Cookie Management
The Rhapsody\Core\Storage\Cookie class offers a static API to set, get, and delete cookies with secure defaults. All cookie values are encrypted using AES-256-CBC and signed with your application's APP_KEY, preventing client-side tampering.
Configuration
Before using cookies, ensure your .env file contains a 32-character encryption key:
APP_KEY=your-32-character-secret-key
Generate one with: php -r "echo bin2hex(random_bytes(16));"
PHP Usage
use Rhapsody\Core\Storage\Cookie;
use Rhapsody\Core\Storage\SameSite;
// Set a cookie (expires in 1 day)
Cookie::set('theme', 'dark', 86400);
// Set a cookie with custom SameSite
Cookie::set('preferences', ['notifications' => true], 3600, '/', null, true, true, SameSite::Strict);
// Get a cookie value
$theme = Cookie::get('theme', 'light');
// Check if a cookie exists
if (Cookie::has('user_id')) {
// ...
}
// Delete a cookie
Cookie::delete('theme');
// Get all cookies (decrypted and decoded)
$all = Cookie::all();
The Cookie::set() method accepts the following parameters (all with secure defaults):
name– the cookie namevalue– can be a string, array, or any JSON-serializable valueexpiry– lifetime in seconds (0 = session cookie)path– cookie path (default:/)domain– optional domainsecure–true(HTTPS only) by defaulthttpOnly–true(no JavaScript access) by defaultsameSite–SameSite::Lax,Strict, orNone(enum)
Twig Functions
The following Twig functions are available to work with cookies directly in your templates:
| Function | Description |
|---|---|
cookie_get(name, default) |
Returns the value of a cookie, or the default if not set. |
cookie_set(name, value, expiry, path, domain, secure, httpOnly, sameSite) |
Sets a cookie (returns nothing, outputs a Set-Cookie header). |
cookie_has(name) |
Returns true if the cookie exists. |
cookie_delete(name, path, domain) |
Deletes the cookie. |
Example in Twig
{# Check if the user has a preference #}
{% if cookie_has('theme') %}
{% set theme = cookie_get('theme') %}
{% else %}
{% set theme = 'light' %}
{% endif %}
{# Set a cookie after a form submission (e.g., from a controller) #}
{{ cookie_set('user_id', user.id, 86400) }}
LocalStorage Management
The Rhapsody\Core\Storage\LocalStorage class generates JavaScript snippets that manipulate the browser's localStorage. This is useful for client-side preferences, temporary data, or caching.
PHP Usage
All methods return a <script> tag ready to be output in your views.
use Rhapsody\Core\Storage\LocalStorage;
// Generate a script that sets a localStorage item
echo LocalStorage::set('user_preferences', ['theme' => 'dark']);
// Generate a script that gets an item and calls a callback
echo LocalStorage::get('user_id', 'handleUserId');
// Remove an item
echo LocalStorage::remove('temp_data');
// Clear all localStorage
echo LocalStorage::clear();
Twig Functions
The following Twig functions output <script> tags directly. Use them with the {{ ... }} syntax (not |raw, as they are already safe).
| Function | Description |
|---|---|
localstorage_set(key, value, jsonEncode = true) |
Sets a localStorage item. If jsonEncode is true, the value is JSON-encoded. |
localstorage_remove(key) |
Removes a localStorage item. |
localstorage_clear() |
Clears all localStorage data. |
Example in Twig
{# Store the user's theme preference client-side #}
{{ localstorage_set('theme', 'dark') }}
{# Remove a temporary flag #}
{{ localstorage_remove('onboarding_seen') }}
Security Considerations
- Encryption: All cookies are encrypted with your
APP_KEY. - HttpOnly: By default, cookies are not accessible via JavaScript, preventing XSS attacks.
- SameSite: Defaults to
Lax, protecting against CSRF. - Secure: By default, cookies are only sent over HTTPS (set
secure=falseonly for local development). - LocalStorage: Data is stored in plain text in the browser – never store sensitive information (like passwords or tokens) in
localStorage.
Testing
In your PHPUnit tests, you can mock the cookie functions or use the Cookie::get() and Cookie::set() methods as usual. For localStorage, the generated JavaScript is not executed in unit tests, so you may want to test the generation logic separately.