-
Notifications
You must be signed in to change notification settings - Fork 2.4k
docs(basics/controllers): clarify session variable usage, locking, best practices #14037
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -212,87 +212,130 @@ Headers, files, cookies and environment variables can be accessed directly from | |
|
|
||
| } | ||
|
|
||
| Why should those values be accessed from the request object and not from the global array like $_FILES? Simple: `because it's bad practice <http://c2.com/cgi/wiki?GlobalVariablesAreBad>`_ and will make testing harder. | ||
| Why should those values be accessed from the request object and not from the global array like $_FILES? Simple: | ||
| `because it's bad practice <http://c2.com/cgi/wiki?GlobalVariablesAreBad>`_ and will make testing harder. | ||
|
|
||
| .. _controller-use-session: | ||
|
|
||
| Reading and writing session variables | ||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | ||
| Sessions and session variables | ||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | ||
|
|
||
| Introduction | ||
| ~~~~~~~~~~~~ | ||
|
|
||
| Sessions allow your application to store data specific to a particular user across multiple HTTP | ||
| requests. Variables are saved server-side and tied to a unique session identifier managed via a | ||
| browser cookie. | ||
|
|
||
| Nextcloud uses PHP’s native session handling but adds several performance optimizations and a | ||
| transparent encryption layer via the ``CryptoSessionData`` class. Data written through the | ||
| ``OCP\ISession`` API benefits from these optimizations and is automatically encrypted at rest. | ||
|
|
||
| .. danger:: | ||
| Never use PHP superglobals like ``$_SESSION``. This bypasses Nextcloud's encryption and | ||
| lifecycle management. leading to race conditions or lost data. | ||
|
|
||
| To set, get or modify session variables, the ISession object has to be injected into the controller. | ||
| Basic usage | ||
| ~~~~~~~~~~~ | ||
|
|
||
| Nextcloud will read existing session data at the beginning of the request lifecycle and close the session afterwards. This means that in order to write to the session, the session has to be opened first. This is done implicitly when calling the set method, but would close immediately afterwards. To prevent this, the session has to be explicitly opened by calling the reopen method. | ||
| Inject the :class:`OCP\\ISession` object via your controller's constructor. | ||
|
|
||
| Alternatively, you can use the ``#[UseSession]`` attribute to automatically open and close the session for you. | ||
| A more complete example: | ||
|
|
||
| .. code-block:: php | ||
| :emphasize-lines: 2,7 | ||
|
|
||
| <?php | ||
| namespace OCA\MyApp\Controller; | ||
|
|
||
| use OCP\AppFramework\Controller; | ||
| use OCP\AppFramework\Http\Attribute\UseSession; | ||
| use OCP\AppFramework\Http\Response; | ||
| use OCP\ISession; | ||
| use OCP\IRequest; | ||
|
|
||
| class PageController extends Controller { | ||
|
|
||
| #[UseSession] | ||
| public function writeASessionVariable(): Response { | ||
| // ... | ||
| public function __construct( | ||
| $appName, | ||
| IRequest $request, | ||
| private ISession $session // PHP 8 property promotion | ||
| ) { | ||
| parent::__construct($appName, $request); | ||
| } | ||
|
|
||
| } | ||
|
|
||
| .. note:: The ``#[UseSession]`` was added in Nextcloud 26 and requires PHP 8.0 or later. If your app targets older releases and PHP 7.x then use the deprecated ``@UseSession`` annotation. | ||
| // Simple (existing) variable retrieval | ||
| public function simpleReads(): Response { | ||
| $this->session->get('last_visit'); | ||
| return new Response(); | ||
| } | ||
|
|
||
| .. code-block:: php | ||
| :emphasize-lines: 2 | ||
| // Default: Implicit locking per write. Good for single operations. | ||
| public function simpleWrite(): Response { | ||
| $this->session->set('last_visit', time()); | ||
| return new Response(); | ||
| } | ||
|
|
||
| /** | ||
| * @UseSession | ||
| */ | ||
| public function writeASessionVariable(): Response { | ||
| // .... | ||
| // Optimization: Keeps session open for the entire method. | ||
| #[UseSession] | ||
| public function batchUpdate(): Response { | ||
| $this->session->set('theme', 'dark'); | ||
| $this->session->set('font_size', '14px'); | ||
| $this->session->remove('fallback_theme'); | ||
| return new Response(); | ||
| } | ||
| } | ||
|
|
||
| When to use ``#[UseSession]`` | ||
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | ||
|
|
||
| In case the session may be read and written by concurrent requests of your application, keeping the session open during your controller method execution may be required to ensure that the session is locked and no other request can write to the session at the same time. When reopening the session, the session data will also get updated with the latest changes from other requests. Using the annotation will keep the session lock for the whole duration of the controller method execution. | ||
| By default, Nextcloud uses an **on-demand locking strategy**: it closes the session immediately after the | ||
| request starts to allow high concurrency, then briefly re-opens and closes it only during a ``set()`` or | ||
| ``remove()`` call. This default "close-early" behavior works for infrequent and standalone writing events | ||
| and prevents one request from blocking another. Developers do not need to do anything special to enable | ||
| this behavior. | ||
|
|
||
| For additional information on how session locking works in PHP see the article about `PHP Session Locking: How To Prevent Sessions Blocking in PHP requests <https://ma.ttias.be/php-session-locking-prevent-sessions-blocking-in-requests/>`_. | ||
| However, in more advanced scenarios (e.g., calling ``set()`` five times in immediate succession) Nextcloud's | ||
| default behavior means the session will open and close five times. This introduces significant I/O | ||
| overhead (even if it does minimize locking). For these cases, Nextcloud supports an optional method-level | ||
| attribute: ``#[UseSession]``. This attribute ensures the session is opened once at the start of your method and | ||
| closed at the end, providing efficiency and correct locking in complex workflows. | ||
|
|
||
| Then session variables can be accessed like this: | ||
| Use the ``#[UseSession]`` attribute when: | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Additionally when regenerating session id within the called code.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Does it make much difference for regenerating?
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Added a bulletpoint |
||
|
|
||
| .. note:: The session is closed automatically for writing, unless you add the ``#[UseSession]`` attribute! | ||
| * **Multiple Writes**: You are calling ``set()`` or ``remove()`` multiple times in one method (prevents | ||
| I/O overhead from repeated open/close cycles). | ||
| * **Reference Manipulation**: You need the session to remain open for complex logic or to ensure data | ||
| consistency throughout the method. | ||
|
|
||
| .. code-block:: php | ||
| .. note:: | ||
| The ``#[UseSession]`` attribute was introduced in Nextcloud 26. Previously, this feature used the | ||
| ``@UseSession`` annotation, which is now deprecated but otherwise equivalent. | ||
|
|
||
| <?php | ||
| namespace OCA\MyApp\Controller; | ||
| Performance and concurrency | ||
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~ | ||
|
|
||
| use OCP\ISession; | ||
| use OCP\IRequest; | ||
| use OCP\AppFramework\Controller; | ||
| use OCP\AppFramework\Http\Attribute\UseSession; | ||
| use OCP\AppFramework\Http\Response; | ||
| PHP natively locks the session file while it is open for writing. If a controller keeps a session open | ||
| unnecessarily, it may block other requests from the same user (e.g., parallel browser tabs or AJAX calls), | ||
| resulting in delays or timeouts. | ||
|
|
||
| class PageController extends Controller { | ||
| By keeping sessions closed except during the brief window of an actual write, Nextcloud ensures a | ||
| responsive, multi-tab, and highly concurrent experience. For more technical background, see `PHP Session | ||
| Locking and How to Prevent It <https://ma.ttias.be/php-session-locking-prevent-sessions-blocking-php-requests/>`_. | ||
|
|
||
| private ISession $session; | ||
| .. warning:: | ||
|
|
||
| public function __construct($appName, IRequest $request, ISession $session) { | ||
| parent::__construct($appName, $request); | ||
| $this->session = $session; | ||
| } | ||
| If your controller method aggressively keeps sessions open, it may block other requests from the same user | ||
| or process (for example, a second browser tab, AJAX request, or background job), resulting in delays or | ||
| deadlocks. | ||
|
|
||
| #[UseSession] | ||
| public function writeASessionVariable(): Response { | ||
| // read a session variable | ||
| $value = $this->session['value']; | ||
| **Available ISession Methods:** | ||
|
|
||
| // write a session variable | ||
| $this->session['value'] = 'new value'; | ||
| } | ||
| The entire ``OCP\\ISession`` API: | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Shouldn't duplicate this list here. Just link to the file instead. |
||
|
|
||
| } | ||
| - ``set(key, value)``, ``get(key)``, ``exists(key)``, ``remove(key)``, ``clear()`` | ||
| - ``reopen()``, ``close()`` | ||
| - ``getId()``, ``regenerateId()`` | ||
|
|
||
| See https://github.com/nextcloud/server/blob/master/lib/public/ISession.php for specifics. | ||
|
|
||
| Setting cookies | ||
| ^^^^^^^^^^^^^^^ | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Either "superglobal" or "Those bypass"