Worker State Between Requests
In worker mode one PHP worker serves many requests. Its state either belongs to a request and is reset when that request ends, or belongs to the worker and persists. This page lists both, and where the reset stops.
What gets reset between requests
OxPHP performs a soft reset between requests. It cleans this state automatically:
- Superglobals.
$_GET,$_POST,$_SERVER,$_COOKIE,$_FILES,$_REQUESTandphp://inputare repopulated with the new request's data. - Output buffers. All output buffers are flushed and cleaned.
- Response headers. The HTTP status code and the headers go back to their defaults. A callback still registered with
header_register_callback()when its request ends is dropped. - Per-request PHP state. Each request starts without the headers
http_get_last_response_headers()returns after anhttp://fetch, the stringstrtok()is splitting, theob_implicit_flush()setting, and any record that output has gone out and where it started (whatheaders_sent($file, $line)reports). Once output has gone out PHP refuses azlib.output_compressionchange, the changeheader('Content-Length: …')also makes, so a fresh record matters. A request paused at a suspension point takes its own with it and finds them again when it resumes. - Error state. The last error (message, file, line, type) and the connection status are cleared. Handlers registered with
set_error_handler()andset_exception_handler()persist. - The session. The session a request opened is closed as that request ends. See Sessions.
- Ini directives the request changed. Changes made with
ini_set(),ignore_user_abort()orerror_reporting()are put back when the request ends. See Ini rollback. - Environment variables set with
putenv(). A variable the request added is removed, and one it overwrote gets its earlier value back. See Environment variables. - The failed request's objects after a fatal error. See Objects after a fatal error.
ob_implicit_flush() starts off in every requestThis holds even with implicit_flush on in php.ini, because PHP applies that directive as a request starts up, and a worker does that once, when it boots. Call ob_implicit_flush() in the request that wants it.
Objects after a fatal error
A fatal error releases the objects whose last reference sat in the failed request's own variables without running their destructors, as PHP does after a fatal. Nothing else loses its destructor. Objects the worker keeps across requests, and those of the other requests in flight on the worker, have their destructors run when they are let go of. On a thread of the async pool the same holds for the other tasks on that thread.
An object of the failed request that outlives the worker's recovery from the fatal also gets its destructor, where PHP-FPM skips it:
- one still held by a shutdown function or output handler of that request, or by its
$_SESSION, when that reference goes; - on PHP 8.5, one passed to a call in the fatal's backtrace (the one
error_get_last()returns), when the request ends, withfatal_error_backtraceson (the default) andzend.exception_ignore_argsoff; - one in a reference cycle, when the cycle collector frees it (with
zend.enable_gcon, the default), which can be while another request is running; - one the worker could not give back, when the worker stops.
Sessions
The session a request opened is closed as that request ends, after its shutdown functions and before its ini changes are put back. That is the order PHP's own request shutdown uses, so the write runs under the request's own settings. The data goes to the save handler, the session id is released, and $_SESSION leaves the symbol table. The next request starts a session under its own cookie, and until it does, session_id() reads '' and $_SESSION is undefined.
A session travels with its request
A worker takes new requests, and resumes paused ones, whenever the request it is running suspends:
- in
oxphp_async_await(),oxphp_sleep()oroxphp_usleep(); - in a
sleep(),usleep(),stream_select()or socket wait taken over byRUNTIME_HOOKS: a read, and with thenetcategory also a connect (new PDO('mysql:…')andnew mysqli(...)included), a TLS handshake, or a write that waits for room; - in a streaming response's flush that waits for its client to make room (see Server-Sent Events).
With RUNTIME_HOOKS on, the worker holds new requests back for a bounded time behind its first request.
PHP's session module keeps one session per thread, and session_start() on a thread with a session open answers true without reading the caller's cookie. So OxPHP takes a request's session off the worker when the request suspends and puts it back when it resumes, as it does with superglobals. That covers the id and $_SESSION, open or closed, and, while the session is open, the save handler and serializer it was opened with. A request run in the meantime that registers a handler of its own or changes session.serialize_handler does not change how the paused session is written.
With the id carried in URLs (session.use_trans_sid on and session.use_only_cookies off, both deprecated since PHP 8.4), the id that PHP's URL rewriter appends to links and forms travels with the request too. So do the SID constant and the variables added with output_add_rewrite_var(). All of them are given back when the request ends.
A request run in that window finds no session: session_id() reads '' and $_SESSION is undefined. Its own session_start() reads its own cookie.
A worker has one session open at a time
The save handler can hold a lock on the open session, and the default files handler locks the session file with a blocking call. A second open on the same thread that waited for that lock would block the very thread the first session needs to release it, and nothing says in advance which session a session_start() will open. So while a request is paused with its session open:
- the worker takes no new request, and new requests wait in the queue for another worker, or for this one, as they do when every worker is busy;
session_start()in any other request on the worker waits until the session is closed and every earlier caller has had its turn.
Everything else on the worker keeps running.
A session counts as open from session_start() until session_write_close(), session_abort(), session_destroy() or the end of the request. After a session_regenerate_id() that fails part way, it counts as open until the end of the request at the latest. A wait inside session_start() itself counts too, such as a save handler reading its store over a connection that RUNTIME_HOOKS suspends.
A request waiting in session_start() is paused the way a sleep is, a quarter of a second at a time. A drain or a cancellation ends it there as it ends a sleep, and so does its time limit, within that quarter of a second and without opening the session.
Three consequences follow:
- Sessions on one worker are open one after another, even for different clients. A request that keeps its session open across a suspension point holds up the sessions of every other request on its worker, and every request the worker has not taken yet, for that long.
- A request that waits, with its session open, for something only a request the worker has not taken yet (or one waiting in
session_start()) can provide does not get it until the session is closed. WithPHP_WORKERS=1, an HTTP call back to the server is not served until then and fails once the caller's timeout or the server's queue wait runs out, and a wait with no timeout of its own never ends. session_start()cannot wait inside a fiber that a userland scheduler such as Revolt or AMPHP started, because OxPHP cannot resume that fiber's context, or in the cleanup a worker runs after a request has come apart (see Where thesleephooks do not suspend). There, while another request on the worker has a session open, it raises a warning and returnsfalse.
The save handler's lock
The save handler keeps whatever it locked until the session is closed. In the default files handler that is an exclusive lock on the session file, taken with a blocking call. A request for the same session id on another worker, or in another process, waits inside the save handler. That wait is a blocking system call on its worker's thread, so it stalls every request that worker is carrying.
Call session_write_close() as soon as the session data is final, and before any oxphp_async_await(), oxphp_sleep() or hooked socket wait. The write and the unlock then happen where your application puts them, and the worker's other sessions and its queue are not held up.
A closed session stays with its request
After session_write_close(), the request that closed the session can still read its id from session_id() and its data from $_SESSION, as under PHP-FPM. Both travel with the request as described above, so it resumes with its own id and data while a request the worker took in between starts its session from its own cookie.
Ini rollback
Anything a request changes with ini_set(), ignore_user_abort() or error_reporting() belongs to that request, as under PHP-FPM, and is put back when the request ends. Most directives (ignore_user_abort, precision, display_errors, error_reporting, default_socket_timeout, user_agent and others) also stay the request's own while it is paused at a suspension point. The worker takes them off, so the requests it runs in the meantime see the baseline, and the paused request resumes with its own values. ini_set('default_socket_timeout', 5) around one HTTP call, or ini_set('display_errors', '1') in a debugging branch, applies to the request that made it and not to the next one.
The baseline is what your bootstrap set, not the value in php.ini. An ini_set() in the outer scope is application configuration: it survives every request, and every request starts with it. That includes ignore_user_abort(true), which, called in the bootstrap, applies to every request the worker serves, streams included (see Server-Sent Events).
The boundaries:
memory_limitand thesession.*settings stay with the worker while it has other requests in flight. The heap and the session module, including the save handler thatsession_set_save_handler()installs, belong to the worker thread. They are not taken off when a request pauses, and are put back only when the worker takes its next request with nothing else running. Until then (while a request is paused, or a fire-and-forget promise is still being reclaimed) a value one request set applies to the requests the worker takes in that window.- Configure sessions the same way in every request, or once in the bootstrap. A session already open keeps the save handler and serializer it was opened with until it is closed. A request waiting in
session_start()for another request's session to close has no such protection: it opens its session with the save handler andsession.*settings in force when its turn comes, which a request run while it waited may have changed. set_time_limit()sets the limit of the request that calls it, butini_get('max_execution_time')reports the worker's. Each request has a time limit of its own (see Request deadlines), andset_time_limit(), orini_set()orini_restore()onmax_execution_time, changes that one and no other.ini_get('max_execution_time')answers with the last value any request set since the worker last had nothing in flight (or the bootstrap's), which on a busy worker need not be the caller's own limit.- A directive whose handler does more than store its value stays on the worker while its request is paused. These are
default_charsetand the encoding settings (they reset mbstring's encodings),zlib.output_compression(it starts an output handler),open_basedir(it resolves a relative path) and the deprecatedassert.*settings. A few that only validate stay too:include_pathwhile OPcache is enabled (set_include_path()included),error_log,date.timezoneanddefault_mimetype. Requests the worker runs while one is paused see the paused request's value, and the directive is put back when the last request in flight ends. - Settings made through a function belong to the worker. What a request sets with
mb_internal_encoding(),date_default_timezone_set()orsetlocale()is not an ini change, and it outlives the request unless the request puts it back. Each PHP thread has a locale of its own, sosetlocale()never reaches requests on other workers, and one set in anoxphp_async()task stays on that async thread for its life. Per thread is not per request: requests running at the same time on one worker share its locale. An extension that calls the C library'ssetlocale()itself, as intl'sNumberFormatter::parse()does, changes the process-wide locale instead. The environment thatputenv()writes is the exception: the worker puts it back itself (see Environment variables). - A directive whose handler refuses to be put back stays as the request left it. It keeps the request's value until the worker next takes a request with nothing else running on it. A paused request whose change is refused when it resumes continues without that change.
- A request ended while one of its directives is being moved recycles the worker. Putting
assert.callbackback drops the callback, and the destructors of what it held run there. If one of them ends the request (a fatal error, or output written to a stream whose client has left), the worker exits underoxphp_worker_recycles_by_reason_total{reason="scheduled"}and its other requests are ended as on any recycle. The request itself is filed as its ending says: a fatal is a500that counts toward the error limit, a departed client is a cancellation that does not, and an exception thrown by such a destructor is the request's uncaught exception and costs nothing more. memory_limitis restored as a value before it is restored as a limit. PHP refuses to lower the allocator's ceiling while more than the new limit is still held. Soini_get()can report the restoredmemory_limitwhile the allocator still enforces the raised one, until the worker's own footprint leaves room for it.opcache.enableis not restored. A request can only turn OPcache off, and only a worker's boot turns it on again. A worker whose request turned it off compiles every file from source for the rest of its life, andini_get('opcache.enable')reads0to say so.
Environment variables
putenv() writes the environment of the whole server process: the one getenv() reads, and the one a child process inherits when exec(), shell_exec(), system() or proc_open() starts it without an $env array. What a request sets there is put back when the request ends, as PHP's own request shutdown does in traditional mode. A variable the request added is removed, and one it overwrote gets its earlier value back. Writes into $_ENV are not putenv() calls and are not put back (see What persists).
The baseline is what your bootstrap set before oxphp_worker(). A request that overwrites such a variable leaves it at the bootstrap's value when it ends, so the next request starts with it again unless something else has set it since. Laravel's Env, which by default writes .env values with putenv(), keeps them for every request.
The boundaries:
- Until the request ends, the value is the process's. There is one environment per process, and a paused request does not take its values with it. Requests on other workers, and requests this worker runs while the setter is paused at a suspension point, read what it set; traditional mode has the same window across workers, since every worker is a thread of one process. Keep a value that belongs to one request, such as one client's credentials, in a variable or in the
$envarray of theproc_open()call that needs it. - The last request to set a name owns it. A request that sets a name another unfinished request on the same worker set replaces that value. When the later request ends, the name goes back to its value from before either of them, so the earlier request does not get its own back.
- Every
putenv()made while a request runs is that request's. A bootstrap that runs lazily, inside the first request, has itsputenv()calls undone when that request ends, so callputenv()beforeoxphp_worker()for values every request should see. Aputenv()made outside every request, by a destructor or callback the worker runs between requests, is put back when the next request on that worker ends. oxphp_async()tasks are not covered. A task runs on an async worker thread, not in the request that started it, and what it sets withputenv()stays for the life of that thread.
What persists
This state survives across requests on the same worker:
- Outer-scope variables. Anything defined before
oxphp_worker()and captured withuse. - Static properties. Class static properties keep their values.
- Database connections. PDO, MySQLi and other persistent connections stay open.
- Autoloaders. Registered autoloaders (Composer, custom) stay active.
- Loaded code. Classes, interfaces, traits and functions stay loaded.
- Ini directives set during bootstrap. An
ini_set()in the outer scope holds for the life of the worker and is what per-request changes roll back to. - Environment variables set during bootstrap. A
putenv()in the outer scope is what a request'sputenv()of the same name is put back to. The environment belongs to the whole process, though: with several workers, a name every worker's bootstrap sets goes back to its value from before the server started (or is removed) for all of them when the worker that set it first exits, until another worker's bootstrap sets it again. See Superglobals. $_ENV. It is deliberately not reset (with PHP's defaultauto_globals_jit=1), because it describes the worker rather than the request. A.envloader's values outlive the boot that wrote them, and a write made inside a request handler lasts just as long, for every later request on that worker and any request multiplexed alongside it. See Superglobals.
Prompts for your agent
These prompts assume an agent with the OxPHP documentation MCP server connected. The agent reads the pages it needs itself.
Find the state that leaks between requests in my OxPHP worker. Read the `features/worker-state` page through the OxPHP documentation MCP server.
Audit my bootstrap and my request handlers for state that survives between requests or is shared by requests that overlap on a worker (statics, globals, `$_ENV`, `putenv()`, `setlocale()`, ini changes), and for sessions left open across a suspension point, then show me the changes that make each one safe.See also
- Worker Mode: how workers boot, serve requests and are configured
- Worker Recycling: when a worker's PHP state is torn down and rebuilt
- Worker Class: the
OxPHP\Server\WorkerAPI a worker script uses - Fiber Multiplexing: what several requests in flight on one worker share