Alpha ZealPHP is early-stage and under active development. APIs may change between minor versions until v1.0. Feedback and bug reports welcome on GitHub.
API Index — Namespaces, Packages, Reports, Indices

ZealPHP

Table of Contents

Interfaces

FcgiTransport
Socket transport for {@see FastCgiClient} (#289).
CounterBackend
Behavioural contract for Counter backends.
PoolDriver
Connection-library adapter for {@see DbConnectionPool}.
RedisDriver
Behavioural contract for a Redis/Valkey client lib (phpredis or predis).
StoreBackend
Behavioural contract every Store backend implements.

Classes

App
ZealPHP framework core — the single process-wide singleton that owns the OpenSwoole server lifecycle, route table, PSR-15 middleware stack, and all per-request lifecycle configuration.
PackagistDownloads
Combined Packagist download count for the shields.io endpoint badge.
InvalidCacheKeyException
SimpleCacheAdapter
Cache
Cache — Tiered key-value cache (memory + file)
CgiInputStream
php:// stream wrapper for the CGI subprocesses (proc cgi_worker.php and the pooled pool_worker.php).
Dispatcher
CGI execution machinery extracted from App.php (Phase 2 structural refactor).
FastCgiClient
FastCGI 1.0 RESPONDER client for ZealPHP's cgiMode('fcgi') dispatch path.
FastCgiException
Thrown on protocol or I/O error; triggers 502 Bad Gateway in the App::include() dispatch path.
FcgiBlockingTransport
Blocking FastCGI transport (#289) — plain stream_socket_client + blocking fread/fwrite.
FcgiCoroutineTransport
Coroutine-yielding FastCGI transport (#289) — OpenSwoole\Coroutine\Client.
ForkPool
Host-side handle for the fork-per-request CGI runner — App::cgiMode('fork').
IPC
Length-prefixed JSON framing for the native FCGI-style worker pool.
WorkerPool
Master-side pool manager for ZealPHP's native FCGI-style worker pool.
CLI
Command-line interface handling for the ZealPHP server lifecycle (start/stop/restart/status/logs + PID-file management).
AtomicBackend
Default CounterBackend — wraps OpenSwoole\Atomic\Long (a 64-bit SIGNED atomic).
MemcachedCounterBackend
Memcached-backed CounterBackend.
RedisCounterBackend
Redis/Valkey-backed CounterBackend.
Counter
Counter — backend-agnostic atomic integer.
DbConnectionPool
Per-worker pool of database connections — the DB counterpart to {@see \ZealPHP\Store\RedisConnectionPool}.
DbException
Thrown by the DB layer — pool acquire timeouts, exhausted retries, and misconfiguration. Mirrors ZealPHP\Store\StoreException for the Store primitives so callers can catch a ZealPHP-namespaced type rather than a raw \PDOException for pool-level (not query-level) failures.
MysqliDriver
{@see PoolDriver} for \mysqli connections — for code that uses mysqli directly rather than PDO (WordPress's $wpdb, legacy apps, mysqlnd-native code). Like PDO_MYSQL, mysqli rides mysqlnd → php_stream, so its socket I/O IS coroutinized under HOOK_ALL (non-blocking per query) — the full coroutine benefit, not just connection bounding.
PdoDriver
{@see PoolDriver} for \PDO connections — works with any PDO driver (MySQL, PostgreSQL, SQLite, SQL Server, Oracle, …).
PhpInfo
Renders phpinfo() as a self-contained HTML document, restoring Apache+mod_php parity for the CLI SAPI (which otherwise emits a plain-text key => value dump).
ApiIndex
Builds a curated landing for /docs/api/ from the phpDocumentor output.
MarkdownRenderer
Renders the docs/*.md guides to HTML for the /docs/guide/{topic} surface. Shared by route/docs.php (full-page render) and api/docs/page.php (htmx swap) so the conversion + link-rewrite rules never drift between the two.
GithubStars
GitHub stargazer-count cache.
HaltException
Thrown to cleanly halt page execution without killing the worker process.
NetworkException
PSR-18 NetworkExceptionInterface implementation.
RequestException
Client
Coroutine HTTP client (PSR-18). Every method performs real network I/O via OpenSwoole's coroutine client, so it is exercised by live integration use, not unit tests — excluded from coverage measurement (no offline seam).
ConditionalRequest
RFC 9110 conditional-request evaluator — a pure, server-free port of Apache httpd's ap_meets_conditions() (modules/http/http_protocol.c).
RequestFactory
ResponseFactory
ServerRequestFactory
StreamFactory
UploadedFileFactory
UriFactory
PSR-17 UriFactoryInterface implementation backed by OpenSwoole\Core\Psr\Uri.
HtmxResponse
Fluent builder for htmx response headers (HX-*).
LazyServerRequest
Lazy PSR-7 ServerRequest — defers expensive hydration until accessed.
MimeResolver
Multi-suffix MIME metadata resolver — Apache mod_mime find_ct parity.
Request
Response
Thin wrapper around \OpenSwoole\Http\Response. The __call / __get / __set proxies forward to the underlying response — these @method annotations expose the forwarded signatures to static analysis so call sites are statically typed instead of treated as mixed.
HTTPResponse
Typed outbound-HTTP response. Returned by every Http::* call.
HTTP
Ergonomic outbound HTTP wrapper around OpenSwoole\Coroutine\Http\Client.
RequestInput
Backs the mod_php-parity filter_input() / filter_input_array() overrides.
IOStreamWrapper
Auth
Chat
ChatHistory
Data-access helpers for the chat_history table used by the Learn module.
Chatroom
Lesson 22 — multi-room group chat (SQLite persistence, no Redis required).
DB
Demo
Helpers for the /learn demo endpoints — WebSocket fan-out broadcasters, the public-demo rate-limit guard, and the standalone demo-page shell.
Notes
Data-access helpers for the notes table used by the Learn module.
TicTacToe
Tic-tac-toe multiplayer helpers (Build-the-App capstone).
WS
ApacheContext
Per-request scratch tables for Apache mod_php shims (apache_setenv, apache_getenv, apache_note). These exist solely so legacy code lifted onto ZealPHP via the CGI bridge keeps working — modern coroutine handlers do not need this class.
Logger
BasicAuthMiddleware
HTTP Basic Auth Middleware
BlockPhpExtMiddleware
Block .php Extension Middleware
BodyRewriteMiddleware
Body Rewrite Middleware (mod_substitute equivalent)
BodySizeLimitMiddleware
Body Size Limit Middleware — nginx client_max_body_size / Apache LimitRequestBody / PHP post_max_size parity.
CacheControlMiddleware
Cache-Control Middleware
CharsetMiddleware
Charset Middleware
CompressionMiddleware
Compression Middleware (gzip / deflate)
ConcurrencyLimitMiddleware
Concurrency-Limit Middleware
ContentEncodingMiddleware
Content-Encoding Middleware — Apache mod_mime AddEncoding parity.
ContentLanguageMiddleware
Content-Language Middleware — Apache mod_mime AddLanguage parity.
CorsMiddleware
CORS Middleware
CsrfMiddleware
CSRF Protection Middleware.
ETagMiddleware
ETag / Conditional-Request Middleware
ExpiresMiddleware
Expires Middleware (Apache mod_expires equivalent)
HeaderMiddleware
Header Middleware
HealthCheckMiddleware
Health Check Middleware — short-circuits on configured paths and returns App::stats() as JSON. Designed for load-balancer probes, Kubernetes liveness/readiness, and monitoring agents.
HostRouterMiddleware
Host-Router Middleware (nginx server_name virtual-host equivalent)
IniIsolationMiddleware
Snapshot / restore selected php.ini values around each request.
IpAccessMiddleware
IP Access Middleware
LocationHeaderMiddleware
Rewrites the port in an outbound Location header to a configured value.
MergeSlashesMiddleware
Merge Slashes Middleware — Apache MergeSlashes On / nginx merge_slashes.
MimeTypeMiddleware
MIME Type Middleware
ApiDispatchHandler
Terminal of a ZealAPI file's in-file $middleware onion. Once every in-file middleware has called its $next, this invokes the resolved api handler closure (ZealAPI::runHandlerWithContract) and turns the universal-return contract result into a PSR-7 ResponseInterface for the onion:
MiddlewareFrame
One frame of a middleware onion: pairs a PSR-15 middleware with the RequestHandler it wraps, so a chain can be assembled as nested handlers (new MiddlewareFrame($m0, new MiddlewareFrame($m1, $terminal))). Calling handle() runs the middleware's process(), handing it the inner handler as $next. Stateless and cheap — a couple of object fields, no clone-per-step.
PathDispatchHandler
Terminal of an App::when() path-scoped middleware onion. Once every path-scoped middleware has called its $next, this hands control to the router's matchAndDispatch() — route matching + dispatch (including any per-route middleware: and, for /api/*, ZealAPI's in-file $middleware).
RouteDispatchHandler
Terminal of a per-route middleware onion. Once every route-level middleware (the middleware: option / a route group's chain) has called its $next, this hands control back to the router's dispatchMatched() with the matched route + params (baked in at construction, so the chain carries no shared per-request state and is safe under coroutine concurrency).
RangeMiddleware
HTTP Range Request Middleware (RFC 7233)
RateLimitMiddleware
Rate-Limit Middleware (sliding window, per-IP, shared across workers)
RedirectMiddleware
Redirect Middleware — declarative URL redirects, Apache mod_alias parity.
RefererMiddleware
Referer Middleware — nginx valid_referers / $invalid_referer parity.
RequestHeaderMiddleware
Request Header Middleware — Apache mod_headers RequestHeader parity.
RequestIdMiddleware
Request-ID middleware — assign every request a correlation id and echo it on the response, so a single request can be traced across logs, services, and the client. The kind of edge concern you'd add at Traefik/nginx, expressed as an in-process middleware that your handlers can also read.
ReturnMiddleware
Return Middleware — nginx return directive parity.
ScopedMiddleware
Scoped Middleware — apply another middleware only to matching request paths.
SessionStartMiddleware
SetEnvIfMiddleware
SetEnvIf Middleware — Apache mod_setenvif parity.
ZealPHP_IPC_Sender
Destructor-based metadata frame sender. PHP runs destructors even after exit() is called from inside a shutdown function — phpMyAdmin's ResponseRenderer->response() does exactly that. The shutdown chain gets preempted, but a destructor on a static instance still fires, so the parent receives status/headers/cookies regardless of how the request ended.
RequestContext
Per-request state container. Lives on Coroutine::getContext() in coroutine mode (recommended default) so each request gets isolated state freed automatically when the coroutine ends. In legacy superglobals mode it's a process-wide singleton bridging declared properties to PHP's $_GET / $_POST / $_SESSION etc.
ResponseMiddleware
The router / dispatch middleware (innermost PSR-15 layer).
REST
RouteGroup
Route group — the object handed to an App::group() callback. It mirrors the App route registrars (route / nsRoute / nsPathRoute / patternRoute) and nested group(), transparently:
CoSessionManager
Per-coroutine session lifecycle manager (coroutine / superglobals(false) mode).
CoroutineMemorySessionHandler
FileSessionHandler
File-backed \SessionHandlerInterface for ZealPHP.
RedisSessionHandler
Redis-backed session handler for ZealPHP.
StoreSessionHandler
Backend-agnostic session handler — rides whichever backend Store::defaultBackend() is configured with.
TableSessionHandler
Table-as-store + file-as-backing session handler.
SessionManager
OpenSwoole onRequest handler for superglobals mode (App::superglobals(true)).
DemoHelpers
Shared helpers for the ZealPHP OSS website's live-demo routes.
CircuitBreakerBackend
3-state circuit breaker decorator for StoreBackend. Opt-in only: applications that want "Redis down → degrade to Table cache" wrap their RedisBackend in this decorator at boot. Default behaviour is unchanged — apps that don't wrap see the same throw-on-Redis-failure semantics they had before.
MemcachedBackend
Memcached-backed StoreBackend.
PhpredisDriver
phpredis-backed driver. Only instantiable when the redis PHP extension is loaded; the adapter falls back to predis otherwise. Tests skip the phpredis-specific path when the ext isn't present (covered by CI matrix).
PredisDriver
predis-backed driver. Pure PHP — works without ext-redis. Slower than phpredis but parity-tested against the same RedisClientTest cases.
PubSubStopException
Sentinel thrown from inside a SUBSCRIBE consumer to signal clean shutdown.
RedisBackend
Redis/Valkey-backed StoreBackend.
RedisClient
Thin adapter over phpredis (preferred when ext-redis is loaded) or predis (pure-PHP fallback). The ONE place the client lib is referenced by name in ZealPHP — every other class talks to this adapter.
RedisConnectionPool
Per-worker pool of RedisClient connections.
RedisPubSub
Per-worker pub/sub runner.
RedisStreams
Per-worker Redis Streams consumer runner.
Stats
Per-worker counter struct for Store/Counter/Pool/Subscriber observability.
StoreException
Thrown by every public method in the ZealPHP\Store namespace.
TableBackend
Default StoreBackend — wraps OpenSwoole\Table.
TieredBackend
Three-tier-ready hybrid backend — TableBackend as L1 (in-process, ns latency, bounded staleness) + RedisBackend as L2 (cross-node, source of truth, ~µs to ~ms).
TypeCodec
Backend-neutral row (de)serialization.
Store
Store — backend-agnostic key-value store.
StringUtils
TemplateUnavailableException
Thrown when a requested template file does not exist.
LogSinkRegistry
Per-worker registry for the async-log sinks and their consumer-spawn guard.
CapacityException
Thrown when WSRouter's shared OpenSwoole\Table segments (ws_owner, ws_room_members) are full. App handlers catching this should respond with a clear "server at capacity" close to the WebSocket client (close code 1013 — "Try Again Later" — is the standard).
Room
A first-class WebSocket room — cluster-wide membership, presence, fan-out + handler registration. Built on the existing v0.2.40 Store + pub/sub fabric:
WSAuthException
Thrown when a WebSocket routing/room operation is refused by authorization (#234): an unauthenticated WSRouter::ownAuthenticated(), or a Room mutation (join/leave/push) denied by the registered WSRouter::roomAuthorizer().
WSRouter
Cross-server WebSocket routing helper.
ZealAPI
File-based API dispatcher.

Enums

CgiMode
Type-safe enum for App::cgiMode(). The four strategies for dispatching CGI requests (.php files in legacy-CGI mode, and any registered non-.php extension).
CounterBackendKind
Type-safe enum for the Counter backend kind. Symmetric with ZealPHP\Store\StoreBackendKind — accepted directly by Counter::defaultBackend().
Isolation
Type-safe enum for App::isolation() — the single knob that says HOW a request is isolated. It folds the old (processIsolation × enableCoroutine × hookAll × cgiMode) cross-product into one intention-revealing value.
DriverPreference
Type-safe enum for RedisClient's driver selection. Accepted by Store::defaultBackend() via the 'prefer' opt and by RedisClient::__construct()'s opts array.
StoreBackendKind
Type-safe enum for the Store backend kind.

Constants

SID  : mixed = ''

Functions

apache_request_headers()  : array<string, string>
Return all HTTP request headers as an associative array.
getallheaders()  : array<string, string>
Alias for apache_request_headers() — both names exist under mod_php.
apache_response_headers()  : array<string, string>
Return all response headers queued for the current request.
apache_setenv()  : bool
Set a named Apache subprocess environment variable.
apache_getenv()  : string|false
Retrieve a named Apache subprocess environment variable.
apache_note()  : string
Get or set an Apache request note (named annotation attached to the request).
virtual()  : bool
Perform an Apache internal sub-request for $uri.
__z_fire_header_callback()  : void
#357 — fire a registered header_register_callback() exactly once (mod_php keeps a single callback). Two registration sources, drained in order: (1) the subprocess-local override above, which stashes into $GLOBALS['__z_header_callback'] (the common case — autoload off); (2) the framework's utils.php header_register_callback(), active when ZEALPHP_CGI_AUTOLOAD=1, which stashes into the RequestContext memo.
__z_send_meta()  : mixed
Write the metadata frame (status, headers, cookies, optional return value) to STDERR as a single JSON line. Idempotent — subsequent calls are no-ops once $__z_meta_sent is true. Called by the flush() override and the shutdown function so the frame is always sent before the body, regardless of whether the included file streams or buffers.
apache_request_headers()  : array<string, string>
Polyfill for apache_request_headers() in CLI SAPI.
getallheaders()  : array<string, string>
Polyfill for getallheaders() in CLI SAPI — delegates to apache_request_headers().
apache_response_headers()  : array<string, string>
Polyfill for apache_response_headers() in CLI SAPI.
apache_setenv()  : bool
Polyfill for apache_setenv() in CLI SAPI.
apache_getenv()  : mixed
Polyfill for apache_getenv() in CLI SAPI.
apache_note()  : string
Polyfill for apache_note() in CLI SAPI.
virtual()  : bool
Polyfill for virtual() in CLI SAPI.
fork_prepare_request()  : string|null
Populate request superglobals + php://input from a request frame. Returns the absolute file to include, or null on a bad/missing file. (The include itself is done by the CALLER at top-level scope — see the loop — so the included file's top-level variables become real $GLOBALS.)
fork_build_response()  : array<string, mixed>
Build the response frame from the captured state + the include's output.
pool_prepare_request()  : array{file: string, prevCwd: mixed}|array{__error: array}
Prepare per-request state and return the file to include + the prior cwd.
pool_finish_request()  : array<string, mixed>
Capture output and build the response AFTER the global-scope include.
pool_reset_request_state()  : void
Reset all per-request state between pool iterations.
php_session_encode_from_array()  : string
Encode an array into PHP's native php session serialize format (key|serialized_value for each key). Matches the format produced by session.serialize_handler = php (the default in mod_php / phpredis).
php_session_decode_to_array()  : array<string, mixed>
Decode a PHP session string back to an associative array.
zeal_session_opened_handler()  : SessionHandlerInterface|null
Resolve the active custom session handler, guaranteeing the SessionHandlerInterface contract that open() precedes any read()/write()/destroy() (#369). A freshly-resolved handler — session_regenerate_id() / session_write_close() reached without a prior session_start() in this request — was used un-open()ed, and FileSessionHandler's typed $savePath fataled on first write() (breaking the textbook login fixation defence with an uncaught Error).
zeal_session_start()  : bool
zeal_valid_session_id()  : bool
Whether a session id is safe to use in a filesystem path / store key.
zeal_session_strict_should_regenerate()  : bool
session.use_strict_mode provenance decision (#244).
zeal_session_set_save_handler()  : bool
Coroutine-mode override of session_set_save_handler() (#295).
zeal_session_id()  : string|false
Get or set the session ID.
zeal_session_status()  : int
Return the current session status (PHP_SESSION_ACTIVE or PHP_SESSION_NONE).
zeal_session_name()  : string
Get or set the session name (the cookie name, e.g. 'PHPSESSID').
zeal_session_write_close()  : bool
Write session data to the backing store and mark the session inactive.
zeal_session_destroy()  : bool
Destroy the session and delete its backing storage.
zeal_session_unset()  : void
Unset all session variables without destroying the session.
zeal_session_regenerate_id()  : bool
Regenerate the session ID, optionally deleting the old session.
zeal_session_get_cookie_params()  : array{lifetime: int, path: string, domain: string, secure: bool, httponly: bool, samesite?: string}
Get the current session cookie parameters.
zeal_session_set_cookie_params()  : void
Set session cookie parameters.
zeal_session_cache_limiter()  : string
Get or set the session cache limiter (e.g. 'nocache', 'public', 'private').
zeal_session_commit()  : bool
Alias for zeal_session_write_close() — write session data and close.
zeal_session_cache_expire()  : int
Get or set the session cache expiry in minutes.
zeal_session_abort()  : bool
Discard in-memory session changes and reload session data from the file.
zeal_session_encode()  : string
Encode the current session data to PHP's php serialize format string.
zeal_session_decode()  : bool
Decode a session data string and populate the active session.
zeal_session_create_id()  : string|false
Create a new session ID, optionally with a $prefix.
zeal_session_save_path()  : string
Get or set the session save path.
zeal_session_module_name()  : string
Get or set the session module name (e.g. 'files', 'redis').
zeal_session_gc()  : int
Garbage-collect expired sessions for the active storage.
get()  : mixed
Read a value from $_GET by key.
env_flag()  : bool
Read a boolean environment variable using ZealPHP's truthiness convention.
bench_mode_enabled()  : bool
Whether benchmark mode is active (ZEALPHP_BENCH_MODE env flag).
site_url()  : string
Absolute base URL for the ZealPHP OSS site.
site_host()  : string
Return just the host component of site_url().
async_logging_enabled()  : bool
Whether async (coroutine-channel-backed) logging is enabled.
zealphp_log_dir_candidates()  : array<int, string>
Ordered list of directories ZealPHP will try for its logs + PID files, most preferred first. Pure (no I/O, no memoization) so it is unit-testable; the actual pick — the first candidate that is writable or creatable — happens in resolve_log_dir().
resolve_log_dir()  : string|null
Resolve the first writable log directory from zealphp_log_dir_candidates().
cgroup_cpu_quota()  : float|null
The container's CPU allowance from its cgroup CPU quota, or null when there is no quota (unlimited, or not running under a limited cgroup).
default_worker_count()  : int
Default HTTP worker count for a bare php app.php (no ZEALPHP_WORKERS), capped to the container's cgroup CPU quota.
debug_logging_enabled()  : bool
Whether debug logging is enabled.
access_logging_enabled()  : bool
Whether access logging is enabled.
log_file_for()  : string|null
Resolve the absolute path for a named log file.
log_sink_for()  : Channel|null
log_write()  : void
Write a log line to the appropriate sink for $kind.
coprocess()  : mixed
Run a closure in a throwaway child process that HAS the coroutine scheduler, even though the caller does not. This is the escape hatch for parallel I/O from a coroutine-scheduler-OFF worker — i.e. superglobals(true) / enableCoroutine(false) mode (the Symfony/FPM-style lifecycle, where running coroutines in the main worker would race process-wide $_GET/$_POST/$_SESSION and shared framework singletons).
coproc()  : mixed
Thin alias for coprocess() — same fork-a-coroutine-child semantics, so it shares coprocess()'s untestability (forks a child process; only valid in the superglobals(true)+enableCoroutine(false) mode the coverage gate excludes).
jTraceEx()  : string
Produce a Java-style exception trace string.
zapi()  : string
Return the basename (without .php extension) of the calling API file.
elog()  : void
Log a debug message with caller location.
zlog()  : void
Log a structured message to zlog.log with request context.
get_config()  : mixed
Read a site configuration value by key.
get_current_render_time()  : float
Get the current render time since request received and started processing.
indent()  : string
Indent the given text with the given number of spaces.
purify_array()  : array<int|string, mixed>
Convert an iterator or object into an array via JSON round-trip.
uniqidReal()  : string
Generates a unique identifier of a specified length.
access_log()  : void
Write an access log line for the current request.
response_add_header()  : void
Add a header to the current response.
response_set_status()  : void
Sets the HTTP response status code.
response_headers_list()  : array<int, array{0: string, 1: string}>
Retrieves all the response headers.
setcookie()  : bool
Set a response cookie (uopz override of PHP's built-in setcookie()).
setrawcookie()  : bool
Set a raw (URL-encoded) response cookie (uopz override of PHP's built-in setrawcookie()).
header()  : false|void
Set a response header (uopz override of PHP's built-in header()).
http_response_code()  : int|null
Get or set the HTTP response status code (uopz override of PHP's built-in http_response_code()).
zeal_putenv()  : bool
Per-coroutine putenv() — stores the assignment in the request-scoped RequestContext ($g->memo['_env']), which is isolated per coroutine in Mode 4, instead of the process-wide environment. Pairs with getenv().
zeal_getenv()  : string|array<string, string>|false
Per-coroutine getenv() — reads the request-scoped env first (set via putenv()), then the process environment captured at boot (App::$boot_env). No-arg form returns the merged map. $local_only returns only request-scoped variables (matches the native signature).
zeal_shell_exec()  : string|null
Coroutine-safe shell_exec() shim — routes through App::exec().
zeal_system()  : string
Coroutine-safe system() shim — routes through App::exec().
zeal_passthru()  : void
Coroutine-safe passthru() shim — routes through App::exec().
zeal_exec()  : string
Coroutine-safe exec() shim — routes through App::exec().
headers_list()  : array<int, string>
Return all outbound response headers as formatted strings (uopz override of headers_list()).
headers_sent()  : bool
Check whether response headers have already been sent (uopz override of headers_sent()).
header_remove()  : void
Remove a previously set response header (uopz override of header_remove()).
flush()  : void
Force the current output buffer to the client (uopz override of flush()).
ob_flush()  : void
Override of ob_flush() — floor-aware.
ob_end_flush()  : void
Override of ob_end_flush() — floor-aware.
ob_implicit_flush()  : void
Apache mod_php ob_implicit_flush() compatibility shim.
phpinfo()  : bool
mod_php-parity phpinfo(): render a self-contained HTML document instead of the CLI SAPI's plain-text dump. Matches the native signature — echoes output and returns true. Wired via uopz in App::__construct(); the renderer lives in \ZealPHP\Diagnostics\PhpInfo.
php_sapi_name()  : string
mod_php-parity php_sapi_name(): under the CLI SAPI this natively returns "cli", which legacy apps branch on to disable web-only behavior. When an app opts in via App::sapiName('apache2handler') (or 'fpm-fcgi'), this returns the configured value so such code takes its web path. Default (App::$sapi_name === null) returns the real PHP_SAPI — zero behavior change unless explicitly configured.
filter_input()  : mixed
mod_php-parity filter_input(): native filter_input() reads PHP's internal SAPI request tables, which OpenSwoole never populates (so it returns null under CLI).
filter_input_array()  : array<string, mixed>
mod_php-parity filter_input_array(): the array counterpart of filter_input().
header_register_callback()  : bool
mod_php-parity header_register_callback(): native PHP fires the callback when the SAPI is about to send headers — which never happens the normal way under OpenSwoole. ZealPHP stores it per-request (coroutine-safe, in $g->memo) and invokes it once just before the buffered response headers are flushed, so header() calls inside the callback still land. Last registration wins (matches native, which keeps a single callback). Returns false if there's no request context (e.g. called outside a request).
error_log()  : bool
mod_php-parity error_log(): under the CLI SAPI native error_log() writes to stderr / the php.ini error_log path. ZealPHP routes message_type 0 (system logger) and 4 (SAPI logger) into the framework's async log (debug.log, or stderr if logging is disabled) so legacy error_log() calls land where the rest of the app's diagnostics go — the "we have elog for error_log" contract.
apache_request_headers()  : array<string, string>
Apache mod_php getallheaders() / apache_request_headers() — return all inbound request headers with canonical (Hyphen-Capitalized) case.
getallheaders()  : array<string, string>
Alias for apache_request_headers() — return all inbound request headers.
apache_response_headers()  : array<string, string>
Apache mod_php apache_response_headers() — return currently queued outbound headers.
apache_setenv()  : bool
Apache mod_php per-request env table setter (apache_setenv()).
apache_getenv()  : string|false
Apache mod_php per-request env table getter (apache_getenv()).
apache_note()  : string
Apache mod_php apache_note() — per-request note table. Returns previous value.
virtual()  : bool
Apache mod_php virtual() — performs an internal subrequest.
set_time_limit()  : bool
set_time_limit() compatibility shim.
ignore_user_abort()  : int
ignore_user_abort() compatibility shim (uopz override).
connection_status()  : int
Return the connection status for the current request.
connection_aborted()  : int
Return 1 when the client connection has been aborted, 0 otherwise.
output_add_rewrite_var()  : bool
Apache's URL-rewrite output handler — not used in ZealPHP. No-op returning false.
output_reset_rewrite_vars()  : bool
Apache's URL-rewrite output handler reset — not used in ZealPHP. No-op returning true.
is_uploaded_file()  : bool
is_uploaded_file() compatibility shim (uopz override).
_zealphp_tmp_name_matches()  : bool
Recursively test whether $filename is one of the temp-path leaves in a field-major $_FILES[...]['tmp_name'] value (scalar or nested array).
move_uploaded_file()  : bool
move_uploaded_file() compatibility shim (uopz override).
set_error_handler()  : callable|null
Per-request set_error_handler() (uopz override).
restore_error_handler()  : bool
Pop the most recently registered per-request error handler.
set_exception_handler()  : callable|null
Per-request set_exception_handler() (uopz override).
restore_exception_handler()  : bool
Pop the most recently registered per-request exception handler.
register_shutdown_function()  : void
Per-request shutdown function (uopz override of register_shutdown_function()).
error_reporting()  : int
Per-coroutine error_reporting() (uopz override).

Constants

Functions

apache_request_headers()

Return all HTTP request headers as an associative array.

apache_request_headers() : array<string, string>

Shim for apache_request_headers() / getallheaders() on non-Apache SAPIs.

Return values
array<string, string>

getallheaders()

Alias for apache_request_headers() — both names exist under mod_php.

getallheaders() : array<string, string>

This shim makes getallheaders() available on OpenSwoole / CLI SAPIs.

Return values
array<string, string>

apache_response_headers()

Return all response headers queued for the current request.

apache_response_headers() : array<string, string>

Delegates to \ZealPHP\apache_response_headers() which reads from the per-request $g->zealphp_response header list.

Return values
array<string, string>

apache_setenv()

Set a named Apache subprocess environment variable.

apache_setenv(string $variable, string $value[, bool $walk_to_top = false ]) : bool

In ZealPHP this writes into the per-request $g->server bag under the conventional HTTP_* key so subsequent handler code sees the value.

The $walk_to_top parameter is accepted for API compatibility but has no effect (there is no parent-request scope in OpenSwoole).

Parameters
$variable : string
$value : string
$walk_to_top : bool = false
Return values
bool

apache_getenv()

Retrieve a named Apache subprocess environment variable.

apache_getenv(string $variable[, bool $walk_to_top = false ]) : string|false

Returns false when the variable is not set (matching Apache's behaviour).

The $walk_to_top parameter is accepted for API compatibility but has no effect in ZealPHP.

Parameters
$variable : string
$walk_to_top : bool = false
Return values
string|false

apache_note()

Get or set an Apache request note (named annotation attached to the request).

apache_note(string $note_name[, string|null $note_value = null ]) : string

When $note_value is null, returns the current value of the note. When $note_value is provided, sets it and returns the previous value (or an empty string when the note was not previously set).

Parameters
$note_name : string
$note_value : string|null = null
Return values
string

virtual()

Perform an Apache internal sub-request for $uri.

virtual(string $uri) : bool

In ZealPHP this dispatches the URI through the framework's routing stack in-process (similar to Apache's virtual() / mod_include sub-request mechanism). Returns true on success, false on failure.

Parameters
$uri : string
Return values
bool

__z_fire_header_callback()

#357 — fire a registered header_register_callback() exactly once (mod_php keeps a single callback). Two registration sources, drained in order: (1) the subprocess-local override above, which stashes into $GLOBALS['__z_header_callback'] (the common case — autoload off); (2) the framework's utils.php header_register_callback(), active when ZEALPHP_CGI_AUTOLOAD=1, which stashes into the RequestContext memo.

__z_fire_header_callback() : void

MUST be called while the header() override is still active (right after the included file finishes) — NOT from the shutdown function: uopz tears its overrides down before register_shutdown_function runs, so header() calls inside a callback fired at shutdown would not be captured into $__z_headers.

__z_send_meta()

Write the metadata frame (status, headers, cookies, optional return value) to STDERR as a single JSON line. Idempotent — subsequent calls are no-ops once $__z_meta_sent is true. Called by the flush() override and the shutdown function so the frame is always sent before the body, regardless of whether the included file streams or buffers.

__z_send_meta() : mixed

apache_request_headers()

Polyfill for apache_request_headers() in CLI SAPI.

apache_request_headers() : array<string, string>

Reconstructs the canonical header map from $_SERVER HTTP_* keys plus CONTENT_TYPE and CONTENT_LENGTH, matching Apache mod_php behaviour.

Return values
array<string, string>

Map of header name → value.

getallheaders()

Polyfill for getallheaders() in CLI SAPI — delegates to apache_request_headers().

getallheaders() : array<string, string>
Return values
array<string, string>

Map of header name → value.

apache_response_headers()

Polyfill for apache_response_headers() in CLI SAPI.

apache_response_headers() : array<string, string>

Returns the response headers collected so far by the header() override.

Return values
array<string, string>

Map of header name → value.

apache_setenv()

Polyfill for apache_setenv() in CLI SAPI.

apache_setenv(string $variable, string $value[, bool $walk_to_top = false ]) : bool

Stores $value in the subprocess-local $__z_apache_env map (Apache mod_env parity).

Parameters
$variable : string
$value : string
$walk_to_top : bool = false
Return values
bool

apache_getenv()

Polyfill for apache_getenv() in CLI SAPI.

apache_getenv(string $variable[, bool $walk_to_top = false ]) : mixed

Reads from $__z_apache_env; returns false when the variable is not set.

Parameters
$variable : string
$walk_to_top : bool = false

apache_note()

Polyfill for apache_note() in CLI SAPI.

apache_note(string $note_name[, string|null $note_value = null ]) : string

Gets/sets a named note in $__z_apache_notes. Returns the previous value (empty string if unset).

Parameters
$note_name : string
$note_value : string|null = null
Return values
string

virtual()

Polyfill for virtual() in CLI SAPI.

virtual(string $uri) : bool

Internal sub-requests are not supported in the subprocess context — always returns false.

Parameters
$uri : string
Return values
bool

fork_prepare_request()

Populate request superglobals + php://input from a request frame. Returns the absolute file to include, or null on a bad/missing file. (The include itself is done by the CALLER at top-level scope — see the loop — so the included file's top-level variables become real $GLOBALS.)

fork_prepare_request(array<string|int, mixed> $req) : string|null
Parameters
$req : array<string|int, mixed>
Return values
string|null

fork_build_response()

Build the response frame from the captured state + the include's output.

fork_build_response(mixed $result, string $body) : array<string, mixed>
Parameters
$result : mixed

the include's return value

$body : string
Return values
array<string, mixed>

pool_prepare_request()

Prepare per-request state and return the file to include + the prior cwd.

pool_prepare_request(array<string|int, mixed> $req) : array{file: string, prevCwd: mixed}|array{__error: array}

The include itself is performed by the CALLER at GLOBAL scope (see the request loop) — NOT here — so a legacy app's top-level variables ($menu / $submenu in WP's wp-admin) become real $GLOBALS. Including from inside a function made them function-locals, so WP's global $menu resolved to null and uksort($menu, …) fataled. [Issue 1: include scope]

Parameters
$req : array<string|int, mixed>
Return values
array{file: string, prevCwd: mixed}|array{__error: array}

pool_finish_request()

Capture output and build the response AFTER the global-scope include.

pool_finish_request(mixed $result, Throwable|null $error, mixed $prevCwd) : array<string, mixed>
Parameters
$result : mixed

the include's return value (null if it threw)

$error : Throwable|null

exception thrown by the include, if any

$prevCwd : mixed

cwd to restore

Return values
array<string, mixed>

pool_reset_request_state()

Reset all per-request state between pool iterations.

pool_reset_request_state() : void

Clears superglobals ($_SERVER, $_GET, $_POST, $_COOKIE, $_FILES, $_REQUEST, $_SESSION), the raw input buffer, response capture state ($__pw_headers, $__pw_cookies, $__pw_rawcookies, $__pw_status), any queued shutdown functions, and all output buffers.

Performs FPM-style $GLOBALS cleanup (unsets request-scope keys not in the boot snapshot) and, when ext-zealphp is loaded, calls zealphp_process_state_clean() to roll back constants, classes, functions, and included files to the boot baseline.

When ZEALPHP_POOL_FULL_RESET=1 is set, also resets op_array run_time_cache, function-local statics, and class static properties (mirrors CoSessionManager's per-request reset stack from ext-zealphp 0.3.25).

IMPORTANT: Must be called at GLOBAL SCOPE (not inside a function) so that $_SESSION = null and the superglobal resets take effect process-wide.

php_session_encode_from_array()

Encode an array into PHP's native php session serialize format (key|serialized_value for each key). Matches the format produced by session.serialize_handler = php (the default in mod_php / phpredis).

php_session_encode_from_array(array<string, mixed> $data) : string
Parameters
$data : array<string, mixed>
Return values
string

php_session_decode_to_array()

Decode a PHP session string back to an associative array.

php_session_decode_to_array(string $data) : array<string, mixed>

Tries unserialize() first (handles the php_serialize handler format), then falls back to parsing the native php format (key|serialized_value pairs). All unserialize() calls use ['allowed_classes' => ['stdClass']] — see the file-level security note above.

Parameters
$data : string
Return values
array<string, mixed>

zeal_session_opened_handler()

Resolve the active custom session handler, guaranteeing the SessionHandlerInterface contract that open() precedes any read()/write()/destroy() (#369). A freshly-resolved handler — session_regenerate_id() / session_write_close() reached without a prior session_start() in this request — was used un-open()ed, and FileSessionHandler's typed $savePath fataled on first write() (breaking the textbook login fixation defence with an uncaught Error).

zeal_session_opened_handler() : SessionHandlerInterface|null

open() is invoked once per request (flagged in session_params).

Return values
SessionHandlerInterface|null

zeal_session_start()

zeal_session_start() : bool
Return values
bool

zeal_valid_session_id()

Whether a session id is safe to use in a filesystem path / store key.

zeal_valid_session_id(string $id) : bool

Rejects the inputs that would let an attacker-chosen PHPSESSID escape the session save directory: empty/oversized values, NUL bytes, path separators (/, \), and parent-directory references (..). The character set is otherwise left permissive so a legitimate custom/legacy session id is not rejected — the basename() applied at every sess_<id> file sink is the belt-and-suspenders traversal guard.

Parameters
$id : string
Return values
bool

zeal_session_strict_should_regenerate()

session.use_strict_mode provenance decision (#244).

zeal_session_strict_should_regenerate(bool $strictMode, bool $clientSupplied, array<string|int, mixed> $loadedSession[, bool|null $storeEntryExists = null ]) : bool

zeal_valid_session_id() checks only the FORMAT of a client-supplied id; a well-formed but server-never-issued id (a planted/fixated PHPSESSID) still passes it. PHP's session.use_strict_mode=1 rejects any id the server has no record of by minting a fresh one. The session managers reproduce that here: after zeal_session_start() has loaded the store for a CLIENT-SUPPLIED id, an EMPTY result means the id is unrecognised (stale / foreign / never issued) — so it must not be honoured, and a fresh server-generated id is issued in its place. This is the single trust check both CoSessionManager and SessionManager consult, kept here so it is unit-testable without driving a full request through OpenSwoole.

PHP's session.use_strict_mode rejects ids the server NEVER ISSUED. When the caller can tell whether the id had a BACKING STORE ENTRY (file existed / handler returned data), that is the canonical signal (ext-zealphp#2): an issued-but-still-empty session — the cookie sent on a data-less first visit, a redirect, any page that stores nothing — is a KNOWN id and must NOT rotate. The old data-emptiness heuristic rotated those on EVERY request, which (combined with the regenerate→write_close sid desync, fixed alongside) cascaded into rotate-and-lose-every-write. The array heuristic remains the fallback for callers that cannot determine store existence.

Parameters
$strictMode : bool

App::$session_strict_mode.

$clientSupplied : bool

Whether the active id came from the client (cookie/query param) rather than being server-minted.

$loadedSession : array<string|int, mixed>

The session data the store resolved for that id; its emptiness is the FALLBACK signal when $storeEntryExists is unknown.

$storeEntryExists : bool|null = null

Whether the id had a backing store entry at load time ($g->session_params ['session_existed']); null = unknown.

Return values
bool

true when the id must be rotated to a fresh server id.

zeal_session_set_save_handler()

Coroutine-mode override of session_set_save_handler() (#295).

zeal_session_set_save_handler([mixed $handler = null ][, bool $register_shutdown = true ]) : bool

Native session_set_save_handler() registers with PHP's session module, which the zeal_session_* overrides never consult — so a custom handler (Redis, etc.) was silently ignored and sessions fell back to the inline file path. This routes the handler to the slots the framework actually reads, in BOTH scopes:

  • App::$session_handler (process-wide) so every future request and worker sees it — the common boot-time call shape; and
  • the current coroutine's $g->session_params['handler'] (immediate) so a per-request middleware call takes effect for THIS request.

Only the object-handler form is supported (PHP's modern signature). The legacy 6-callable form and a non-handler argument are rejected (return false), as the zeal_session_* core requires a \SessionHandlerInterface.

Parameters
$handler : mixed = null

A \SessionHandlerInterface instance.

$register_shutdown : bool = true

Accepted for signature parity; unused (the managers own the write-close lifecycle).

Return values
bool

true when wired, false for an unsupported argument.

zeal_session_id()

Get or set the session ID.

zeal_session_id([string|null $id = null ]) : string|false

With no argument: reads the PHPSESSID (or custom session name) cookie from $g->cookie. When no cookie is present a fresh ID is generated via session_create_id() and stashed in $g->cookie. A malformed inbound ID (path traversal, NUL, oversized) is silently replaced with a fresh one.

NOTE: this function only validates id FORMAT. The session.use_strict_mode PROVENANCE check (rotating a well-formed but never-issued id that loads an empty session — #244) lives in the session managers, which call zeal_session_strict_should_regenerate() after the store has been read.

Parameters
$id : string|null = null

Pass a string to set the session ID explicitly.

Return values
string|false

The current (or newly-set) session ID.

zeal_session_status()

Return the current session status (PHP_SESSION_ACTIVE or PHP_SESSION_NONE).

zeal_session_status() : int

Mode-aware: in superglobals mode inspects $GLOBALS['_SESSION']; in coroutine mode checks whether the typed $g->session slot is initialised (it is unset() by zeal_session_write_close() / zeal_session_destroy() to mark a session inactive).

Return values
int

zeal_session_name()

Get or set the session name (the cookie name, e.g. 'PHPSESSID').

zeal_session_name([string|null $name = null ]) : string

Stored per-request in $g->session_params['name'].

Parameters
$name : string|null = null

Pass null to read the current value.

Return values
string

The current (or newly-set) session name.

zeal_session_write_close()

Write session data to the backing store and mark the session inactive.

zeal_session_write_close() : bool

Coroutine-safe replacement for PHP's session_write_close(). Performs a read-merge-write under flock(LOCK_EX) (file backend) or an optimistic WATCH/MULTI/EXEC retry loop (custom \SessionHandlerInterface) to guard against concurrent-coroutine last-write-wins data loss on the same session ID. The merge is shallow — top-level keys added by a concurrent request survive, but conflicting nested arrays are last-write-wins.

After writing, $g->session (coroutine mode) or $GLOBALS['_SESSION'] (superglobals mode) is unset() so zeal_session_status() returns PHP_SESSION_NONE for the remainder of the request.

Return values
bool

zeal_session_destroy()

Destroy the session and delete its backing storage.

zeal_session_destroy() : bool

Deletes the session file (or calls \SessionHandlerInterface::destroy() for custom backends), removes $g->session and $_SESSION, and clears the session cookie from $g->cookie. Sets $g->_session_started to false.

Return values
bool

zeal_session_unset()

Unset all session variables without destroying the session.

zeal_session_unset() : void

Resets $g->session to [] and, in superglobals mode, also clears $GLOBALS['_SESSION']. The session file / backend entry is NOT deleted — call zeal_session_destroy() to remove it entirely.

zeal_session_regenerate_id()

Regenerate the session ID, optionally deleting the old session.

zeal_session_regenerate_id([bool $delete_old_session = false ]) : bool

Coroutine-safe replacement for PHP's session_regenerate_id(). Copies the current in-memory session data to the new ID via the active backend (custom \SessionHandlerInterface or file), then emits a fresh Set-Cookie header so the client switches to the new ID. Gated by App::$session_lifecycle and session.use_cookies — same guards as zeal_session_start().

Parameters
$delete_old_session : bool = false

When true, the old session file/entry is deleted.

Return values
bool

Get the current session cookie parameters.

zeal_session_get_cookie_params() : array{lifetime: int, path: string, domain: string, secure: bool, httponly: bool, samesite?: string}

Returns the array stored in $g->session_params['cookie_params'], falling back to safe defaults (path='/', httponly=true, samesite='Lax').

Return values
array{lifetime: int, path: string, domain: string, secure: bool, httponly: bool, samesite?: string}

Set session cookie parameters.

zeal_session_set_cookie_params(int|array<string, mixed> $lifetime_or_options[, string $path = null ][, string $domain = null ][, bool $secure = null ][, bool $httponly = null ]) : void

Accepts either the positional-args form (PHP < 8.0 style) or an options array (PHP 8.0+ session_set_cookie_params(array $options) style). Both are merged over the defaults ['lifetime'=>0, 'path'=>'/', 'domain'=>'', 'secure'=>false, 'httponly'=>false, 'samesite'=>'Lax'].

Parameters
$lifetime_or_options : int|array<string, mixed>

Integer lifetime in seconds, or an options array.

$path : string = null
$domain : string = null
$secure : bool = null
$httponly : bool = null

zeal_session_cache_limiter()

Get or set the session cache limiter (e.g. 'nocache', 'public', 'private').

zeal_session_cache_limiter([string|null $cache_limiter = null ]) : string

Stored per-request in $g->cache_limiter. Defaults to 'nocache'.

Parameters
$cache_limiter : string|null = null

Pass null to read the current value.

Return values
string

zeal_session_commit()

Alias for zeal_session_write_close() — write session data and close.

zeal_session_commit() : bool

Mirrors PHP's session_commit(), which is itself an alias of session_write_close().

Return values
bool

zeal_session_cache_expire()

Get or set the session cache expiry in minutes.

zeal_session_cache_expire([int|null $cache_expire = null ]) : int

Stored per-request in $g->cache_expire. Defaults to 180 when not set.

Parameters
$cache_expire : int|null = null

Pass null to read the current value.

Return values
int

zeal_session_abort()

Discard in-memory session changes and reload session data from the file.

zeal_session_abort() : bool

Mirrors PHP's session_abort(): any writes to $g->session or $_SESSION since the last session_start() are thrown away, and the session data is re-read from the session file on disk. Returns true always.

Return values
bool

zeal_session_encode()

Encode the current session data to PHP's php serialize format string.

zeal_session_encode() : string

Reads from $GLOBALS['_SESSION'] in superglobals mode, or from RequestContext::instance()->session in coroutine mode.

Return values
string

zeal_session_decode()

Decode a session data string and populate the active session.

zeal_session_decode(string $data) : bool

Mirrors PHP's session_decode(): parses $data via php_session_decode_to_array() and stores the result in both $g->session and $GLOBALS['_SESSION'] (in superglobals mode). Returns false when $data is empty or decodes to an empty array.

Parameters
$data : string
Return values
bool

zeal_session_create_id()

Create a new session ID, optionally with a $prefix.

zeal_session_create_id([string $prefix = '' ]) : string|false

Thin wrapper around PHP's session_create_id().

Parameters
$prefix : string = ''

Optional prefix prepended to the generated ID.

Return values
string|false

The new session ID, or false on failure.

zeal_session_save_path()

Get or set the session save path.

zeal_session_save_path([string|null $path = null ]) : string

Stored per-request in $g->session_params['save_path']. Defaults to '/var/lib/php/sessions' when not set.

Parameters
$path : string|null = null

Pass null to read the current value.

Return values
string

The current (or newly-set) save path.

zeal_session_module_name()

Get or set the session module name (e.g. 'files', 'redis').

zeal_session_module_name([string|null $module = null ]) : string

Stored per-request in $g->session_module_name. Defaults to 'files' when not set. This is a ZealPHP-internal tracking field; the actual backend is determined by the registered \SessionHandlerInterface.

Parameters
$module : string|null = null

Pass null to read the current value.

Return values
string

zeal_session_gc()

Garbage-collect expired sessions for the active storage.

zeal_session_gc(int $maxlifetime) : int

ZealPHP replaced PHP's probabilistic per-request GC (session.gc_probability) with deterministic, explicit collection — but nothing called it, so on a long-lived worker sess_* files (default storage) accumulated until inodes exhausted, and a leaked/abandoned PHPSESSID stayed replayable forever. App::run() now schedules this on a worker-0 timer (see App::registerSessionGc()).

A registered SessionHandlerInterface owns its own GC (Redis/Table handlers already expire rows server-side); the default inline file path sweeps sess_* files whose mtime is older than $maxlifetime seconds.

Parameters
$maxlifetime : int

Seconds of inactivity after which a session expires.

Return values
int

Number of file entries removed (handler backends return their own count, or 0).

get()

Read a value from $_GET by key.

get(string $key[, mixed $default = null ]) : mixed
Parameters
$key : string
$default : mixed = null

env_flag()

Read a boolean environment variable using ZealPHP's truthiness convention.

env_flag(string $name, bool $default) : bool

Returns $default when the variable is unset or empty. Otherwise, returns false when the value is one of '0', 'false', 'off', 'no', or 'none' (case-insensitive); returns true for everything else.

Parameters
$name : string
$default : bool
Return values
bool

bench_mode_enabled()

Whether benchmark mode is active (ZEALPHP_BENCH_MODE env flag).

bench_mode_enabled() : bool

Bench mode disables all logging to avoid I/O overhead skewing results. The result is memoised after the first call.

Return values
bool

site_url()

Absolute base URL for the ZealPHP OSS site.

site_url([string $path = '' ]) : string

Resolution order:

  1. ZEALPHP_SITE_URL env var.
  2. ZEALPHP_SITE_HOST env var (scheme https:// prepended if absent).
  3. Hard-coded fallback https://php.zeal.ninja.

When $path is non-empty it is appended with a single / separator. The result is memoised after the first call.

Parameters
$path : string = ''
Return values
string

site_host()

Return just the host component of site_url().

site_host() : string

Falls back to the full site_url() string when parse_url() cannot extract a host (e.g. a bare domain without scheme).

Return values
string

async_logging_enabled()

Whether async (coroutine-channel-backed) logging is enabled.

async_logging_enabled() : bool

Controlled by the ZEALPHP_LOG_ASYNC env flag (default true). The result is memoised after the first call.

Return values
bool

zealphp_log_dir_candidates()

Ordered list of directories ZealPHP will try for its logs + PID files, most preferred first. Pure (no I/O, no memoization) so it is unit-testable; the actual pick — the first candidate that is writable or creatable — happens in resolve_log_dir().

zealphp_log_dir_candidates() : array<int, string>

Order:

  1. $ZEALPHP_LOG_DIR — explicit override, when set.
  2. /tmp/zealphp — the shared default, kept first for BC (used whenever the current user can create/write it: single-user box, root, or fresh box).
  3. Per-user fallbacks for the collision case where /tmp/zealphp already exists owned by ANOTHER user (e.g. root started a server there first), so this user cannot write it: $XDG_RUNTIME_DIR/zealphp, then a uid/user- suffixed temp dir (sys_get_temp_dir()/zealphp-<uid>). These keep us off a non-writable /tmp/zealphp without polluting the project tree, and resolve deterministically so start and stop/status agree on the same dir.
  4. Project-tree last resorts (./tmp/zealphp, ./logs/zealphp).
Return values
array<int, string>

resolve_log_dir()

Resolve the first writable log directory from zealphp_log_dir_candidates().

resolve_log_dir() : string|null

Creates the directory (with 0775 permissions, recursively) if it does not yet exist. Memoises the result so the filesystem is only probed once per worker lifetime. Returns null when no candidate is writable or creatable.

Return values
string|null

cgroup_cpu_quota()

The container's CPU allowance from its cgroup CPU quota, or null when there is no quota (unlimited, or not running under a limited cgroup).

cgroup_cpu_quota() : float|null

Reads cgroup v2 (/sys/fs/cgroup/cpu.max = "quota period") first, then v1 (cpu.cfs_quota_us / cpu.cfs_period_us). Returns quota ÷ period as a float (e.g. 6.0 for "600000 100000"); null for "max" / unset / unreadable.

Return values
float|null

default_worker_count()

Default HTTP worker count for a bare php app.php (no ZEALPHP_WORKERS), capped to the container's cgroup CPU quota.

default_worker_count([int $preferred = 4 ]) : int

OpenSwoole's own default when worker_num is unset is swoole_cpu_num() = the HOST cpu count — so a bare boot in a CPU-limited Docker container over-spawns (e.g. 24 workers on a 4–6 CPU container) and gets OOM-killed. Returns max(1, min($preferred, floor(cgroup_quota))); when there is no cgroup quota it returns the conservative $preferred (NOT the host count).

Parameters
$preferred : int = 4

desired worker count when unconstrained (default 4)

Return values
int

debug_logging_enabled()

Whether debug logging is enabled.

debug_logging_enabled() : bool

Always false in bench mode. Controlled by ZEALPHP_DEBUG_LOG or the legacy ZEALPHP_ELOG env var (default true when neither is set). The result is memoised after the first call.

Return values
bool

access_logging_enabled()

Whether access logging is enabled.

access_logging_enabled() : bool

Always false in bench mode. Controlled by the ZEALPHP_ACCESS_LOG env flag (default true). The result is memoised after the first call.

Return values
bool

log_file_for()

Resolve the absolute path for a named log file.

log_file_for(string $kind) : string|null

$kind is one of 'access', 'zlog', or 'debug'. Checks (in order):

  1. Kind-specific env var (ZEALPHP_ACCESS_LOG_FILE, ZEALPHP_ZLOG_FILE, ZEALPHP_DEBUG_LOG_FILE).
  2. ZEALPHP_LOG_FILE (generic override, all kinds).
  3. resolve_log_dir() + kind-specific filename (access.log, zlog.log, debug.log).

Returns null when no writable log directory can be found. Results are memoised per kind.

Parameters
$kind : string
Return values
string|null

log_sink_for()

log_sink_for(string $path) : Channel|null
Parameters
$path : string
Return values
Channel|null

log_write()

Write a log line to the appropriate sink for $kind.

log_write(string $message[, string $kind = 'debug' ]) : void

Pushes to the async Channel sink when one is available (non-blocking, coroutine-safe). Falls through to a synchronous fopen/fwrite when called outside a coroutine or when the channel push fails. Writes to php://stderr as a last resort when no log file can be resolved.

Note: uses php://stderr directly (not error_log()) in fallback paths because error_log() is uopz-overridden to route into this very function — calling it would recurse infinitely.

Parameters
$message : string
$kind : string = 'debug'

coprocess()

Run a closure in a throwaway child process that HAS the coroutine scheduler, even though the caller does not. This is the escape hatch for parallel I/O from a coroutine-scheduler-OFF worker — i.e. superglobals(true) / enableCoroutine(false) mode (the Symfony/FPM-style lifecycle, where running coroutines in the main worker would race process-wide $_GET/$_POST/$_SESSION and shared framework singletons).

coprocess(callable $taskLogic[, bool $wait = true ]) : mixed

The child is spawned with OpenSwoole's coroutine runtime enabled, so inside $taskLogic you can go() + Channel + hooked I/O (curl, file_get_contents, PDO over the network, Co\System::exec, ...) and they run concurrently. The call BLOCKS until the child finishes (when $wait is true) and returns whatever the child echoed — so serialise structured results (json_encode in the child, json_decode in the caller).

Cost & caveats:

  • One proc-style fork per call (~ms). Worth it when a request needs N genuinely-parallel slow I/O calls; not worth it for a single call or CPU-bound work.
  • The child is a FRESH process — it does NOT inherit your framework container, DB connection pool, or request state. Pass everything it needs as captured variables; do raw I/O inside (it can't reach Symfony services / Doctrine's managed connection).
  • Refused when superglobals(false) (coroutine mode) — there you already have a scheduler, so just go() directly.

Example (3 parallel HTTP fetches from a sequential worker):

$json = coprocess(function () {
    $chan = new \OpenSwoole\Coroutine\Channel(3);
    foreach (['a','b','c'] as $svc) {
        go(function () use ($svc, $chan) {
            $chan->push([$svc => file_get_contents("https://api/$svc")]);
        });
    }
    $out = [];
    for ($i = 0; $i < 3; $i++) { $out += $chan->pop(); }
    echo json_encode($out);            // returned to the caller as a string
});
$data = json_decode($json, true);
Parameters
$taskLogic : callable

The logic to run in the coroutine-enabled child. Receives the OpenSwoole\Process as its argument.

$wait : bool = true

Whether to block until the child completes. Default true.

Return values
mixed

The child's echoed output (string) when $wait is true.

coproc()

Thin alias for coprocess() — same fork-a-coroutine-child semantics, so it shares coprocess()'s untestability (forks a child process; only valid in the superglobals(true)+enableCoroutine(false) mode the coverage gate excludes).

coproc(callable $taskLogic) : mixed
Parameters
$taskLogic : callable
Tags
codeCoverageIgnore

jTraceEx()

Produce a Java-style exception trace string.

jTraceEx(Throwable $e[, array<int, string>|null $seen = null ]) : string
Parameters
$e : Throwable
$seen : array<int, string>|null = null

array passed to recursive calls to accumulate trace lines already seen; leave as null when calling this function

Return values
string

of array strings, one entry per trace line

zapi()

Return the basename (without .php extension) of the calling API file.

zapi() : string

Used inside api/ handlers to obtain the endpoint name for logging without hard-coding the filename. Reads one frame from debug_backtrace().

Return values
string

elog()

Log a debug message with caller location.

elog(string $message[, string $tag = "*" ][, int $limit = 1 ]) : void

Writes to the debug log (debug.log) when debug_logging_enabled() is true. Messages tagged 'wordpress' are silently suppressed to avoid noise from WordPress's verbose internal logging.

Parameters
$message : string

The message to log.

$tag : string = "*"

The tag to associate with the log message. Default "*".

$limit : int = 1

Stack depth passed to debug_backtrace(). Default 1.

zlog()

Log a structured message to zlog.log with request context.

zlog(mixed $log[, string $tag = "system" ][, mixed $filter = null ][, bool $invert_filter = false ]) : void

Writes caller file/line, request URL, request ID, and render timer alongside the message. Valid $tag values: 'system', 'fatal', 'error', 'warning', 'info', 'debug'. Messages with unknown tags are silently dropped. No-op when debug_logging_enabled() is false.

Parameters
$log : mixed

The message or data to log (arrays/objects are JSON-encoded).

$tag : string = "system"

The tag to categorize the log entry. Default "system".

$filter : mixed = null

Optional URI substring filter; skips logging when the current REQUEST_URI does not contain this string.

$invert_filter : bool = false

Whether to invert the filter logic. Default false.

get_config()

Read a site configuration value by key.

get_config(string $key) : mixed

Decodes the global $__site_config JSON string and returns the value for $key, or null when the key is absent or the config is not valid JSON.

Parameters
$key : string

get_current_render_time()

Get the current render time since request received and started processing.

get_current_render_time() : float

This function calculates and returns the current render time.

Return values
float

The current render time in seconds.

indent()

Indent the given text with the given number of spaces.

indent(string $string[, int $indend = 4 ]) : string
Parameters
$string : string
$indend : int = 4

Number of lines to indent

Return values
string

purify_array()

Convert an iterator or object into an array via JSON round-trip.

purify_array(mixed $obj) : array<int|string, mixed>
Parameters
$obj : mixed
Return values
array<int|string, mixed>

uniqidReal()

Generates a unique identifier of a specified length.

uniqidReal([int $length = 13 ]) : string
Parameters
$length : int = 13

The length of the unique identifier to generate. Default is 13.

Return values
string

The generated unique identifier.

access_log()

Write an access log line for the current request.

access_log([int $status = 200 ][, int $length = 0 ][, float|null $durationSec = null ]) : void

Delegates to App::formatAccessLogLine() so the entry honours App::$access_log_format (Apache LogFormat / CustomLog parity) and the trusted-proxy X-Forwarded-For walk in App::clientIp(). No-op when access_logging_enabled() is false.

Parameters
$status : int = 200

The HTTP status code to log.

$length : int = 0

The response body length in bytes.

$durationSec : float|null = null

Request duration in seconds, or null to omit.

response_add_header()

Add a header to the current response.

response_add_header(string $key, string $value[, bool $replace = true ]) : void

Delegates to $g->zealphp_response->header(). The 3rd argument is the $replace flag (PHP header() semantics): true (default) drops prior same-name entries so this value wins; false is the APPEND form, keeping earlier same-name headers so multiple Link / WWW-Authenticate / CSP headers all reach the wire (#260).

Note: the parameter was historically named $ucwords and passed as a DEAD 3rd argument to a 2-param method (silently ignored). It is repurposed here as $replace — every existing 2-arg call keeps the replace-by-default behaviour it already had on the wire, so this is BC.

Parameters
$key : string

The header name.

$value : string

The header value.

$replace : bool = true

Whether to replace a prior same-name header (default true). Pass false to append.

response_set_status()

Sets the HTTP response status code.

response_set_status(int $status) : void

Coerces out-of-range codes to 500 (Apache parity, RFC 7230 §3.1.2 — a status code is three digits, 100-599). This is the single chokepoint every status sink converges on — http_response_code(), header("HTTP/1.1 600 …") and the Status: CGI form all route here — so an out-of-range code never reaches the wire as a silent 200 (OpenSwoole's one-arg status() drops unknown codes). The coercion is logged once here via App::coerceStatusCode() (#292).

Parameters
$status : int

The HTTP status code to set for the response.

response_headers_list()

Retrieves all the response headers.

response_headers_list() : array<int, array{0: string, 1: string}>
Return values
array<int, array{0: string, 1: string}>

An associative array of all the response headers.

setcookie()

Set a response cookie (uopz override of PHP's built-in setcookie()).

setcookie(string $name[, string $value = "" ][, int|array{expires?: int, path?: string, domain?: string, secure?: bool, httponly?: bool, samesite?: string} $expire_or_options = 0 ][, string $path = "" ][, string $domain = "" ][, bool $secure = false ][, bool $httponly = false ][, string $samesite = '' ]) : bool

Validates the cookie name and value for control characters (matching PHP native behaviour since PHP 7). Supports the PHP 7.3+ options-array form for $expire_or_options. Delegates to $g->zealphp_response->cookie().

Parameters
$name : string
$value : string = ""
$expire_or_options : int|array{expires?: int, path?: string, domain?: string, secure?: bool, httponly?: bool, samesite?: string} = 0
$path : string = ""
$domain : string = ""
$secure : bool = false
$httponly : bool = false
$samesite : string = ''
Return values
bool

setrawcookie()

Set a raw (URL-encoded) response cookie (uopz override of PHP's built-in setrawcookie()).

setrawcookie(string $name[, string $value = "" ][, int|array{expires?: int, path?: string, domain?: string, secure?: bool, httponly?: bool} $expire_or_options = 0 ][, string $path = "" ][, string $domain = "" ][, bool $secure = false ][, bool $httponly = false ]) : bool

Like setcookie() but the value is sent as-is without URL-encoding. Supports the PHP 7.3+ options-array form for $expire_or_options. Because the raw variant does NOT url-encode, PHP 8.4 rejects a name or value carrying any of ,; \t\r\n\013\014\0 by throwing a ValueError (not a warning) — this override mirrors that so legacy code relying on the throw behaves identically (#291). setcookie() keeps its warn-and-return-false behaviour because it url-encodes the value, so the same characters are harmless there.

Parameters
$name : string
$value : string = ""
$expire_or_options : int|array{expires?: int, path?: string, domain?: string, secure?: bool, httponly?: bool} = 0
$path : string = ""
$domain : string = ""
$secure : bool = false
$httponly : bool = false
Return values
bool

header()

Set a response header (uopz override of PHP's built-in header()).

header(string $header[, bool $replace = true ][, int|null $http_response_code = null ]) : false|void

Guards against CRLF/NUL injection (HTTP response splitting). Recognises the Apache mod_php status-line forms:

  • header("HTTP/1.1 404 Not Found") — sets the response status code.
  • header("Status: 404 Not Found") — CGI variant; sets the status code.

When $replace is true, any previously queued header with the same name (case-insensitive) is removed before the new value is added.

Parameters
$header : string
$replace : bool = true
$http_response_code : int|null = null
Return values
false|void

http_response_code()

Get or set the HTTP response status code (uopz override of PHP's built-in http_response_code()).

http_response_code([int|null $code = null ]) : int|null

When $code is null, returns the current status. Otherwise sets it and returns null.

Parameters
$code : int|null = null
Return values
int|null

zeal_putenv()

Per-coroutine putenv() — stores the assignment in the request-scoped RequestContext ($g->memo['_env']), which is isolated per coroutine in Mode 4, instead of the process-wide environment. Pairs with getenv().

zeal_putenv(string $assignment) : bool

The process environment stays at its boot value, so concurrent requests no longer race putenv() (a process-level landmine in any persistent server).

Trade-off: subprocesses (proc_open) do NOT inherit a request-scoped putenv — use it for request-scoped config (tenant id, locale), not for child-process environment. Registered only in coroutine-isolated mode (Mode 4).

Parameters
$assignment : string

"NAME=value" to set, or "NAME" to unset.

Return values
bool

zeal_getenv()

Per-coroutine getenv() — reads the request-scoped env first (set via putenv()), then the process environment captured at boot (App::$boot_env). No-arg form returns the merged map. $local_only returns only request-scoped variables (matches the native signature).

zeal_getenv([string|null $name = null ][, bool $local_only = false ]) : string|array<string, string>|false
Parameters
$name : string|null = null
$local_only : bool = false
Return values
string|array<string, string>|false

zeal_shell_exec()

Coroutine-safe shell_exec() shim — routes through App::exec().

zeal_shell_exec(string $cmd) : string|null

Registered as a uopz override of the shell_exec builtin when exec hooking is enabled (see App::$hook_exec). Because the PHP backtick operator compiles down to a shell_exec() call, overriding shell_exec also makes `cmd` coroutine-safe transparently.

Preserves the builtin's documented return shape: null when the command produced no output and failed, otherwise the captured stdout string.

Parameters
$cmd : string
Return values
string|null

zeal_system()

Coroutine-safe system() shim — routes through App::exec().

zeal_system(string $cmd[, int|null &$code = null ]) : string

Echoes the full output (like the builtin) and returns the last line of output, writing the exit code into $code by reference.

Parameters
$cmd : string
$code : int|null = null

Exit status, written by reference.

Tags
param-out

int $code

Return values
string

zeal_passthru()

Coroutine-safe passthru() shim — routes through App::exec().

zeal_passthru(string $cmd[, int|null &$code = null ]) : void

Echoes the raw output and writes the exit code into $code by reference.

Parameters
$cmd : string
$code : int|null = null

Exit status, written by reference.

Tags
param-out

int $code

zeal_exec()

Coroutine-safe exec() shim — routes through App::exec().

zeal_exec(string $cmd[, array<int, string> &$output = [] ][, int|null &$code = null ]) : string

Appends each output line to $output (like the builtin) and writes the exit code into $code by reference. Returns the last line of output.

Parameters
$cmd : string
$output : array<int, string> = []

Output lines, appended by reference.

$code : int|null = null

Exit status, written by reference.

Tags
param-out

int $code

Return values
string

headers_list()

Return all outbound response headers as formatted strings (uopz override of headers_list()).

headers_list() : array<int, string>

Each element is formatted as "Name: value".

Return values
array<int, string>

headers_sent()

Check whether response headers have already been sent (uopz override of headers_sent()).

headers_sent([string|null &$file = null ][, int|null &$line = null ]) : bool

Under OpenSwoole, headers are considered "sent" when the underlying openswoole_response is no longer writable. The $file and $line out-parameters are not populated (no PHP output-started tracking in this runtime).

Parameters
$file : string|null = null

Optional. If provided, this will be set to the filename where output started.

$line : int|null = null

Optional. If provided, this will be set to the line number where output started.

Return values
bool

Returns true if headers have already been sent, false otherwise.

header_remove()

Remove a previously set response header (uopz override of header_remove()).

header_remove([string|null $name = null ]) : void

With no argument (or null), clears all queued response headers. Otherwise removes all headers matching $name (case-insensitive).

Parameters
$name : string|null = null

flush()

Force the current output buffer to the client (uopz override of flush()).

flush() : void

In main-worker mode, this switches the response into streaming mode: headers are flushed once, then body chunks are written via openswoole_response->write(). Subsequent echo + flush() calls stream incrementally. No-op when the response is no longer writable or no response context is available.

ob_flush()

Override of ob_flush() — floor-aware.

ob_flush() : void

Native ob_flush() passes the current buffer's content to the PARENT buffer without closing it. App-level buffers nested ABOVE the framework's capture buffer ($g->_ob_floor, recorded by App::executeFile()) must keep that native semantic; only at the framework floor does "flush" mean "stream to the client".

ob_end_flush()

Override of ob_end_flush() — floor-aware.

ob_end_flush() : void

Native ob_end_flush() pops the current buffer INTO ITS PARENT. The old shim unconditionally streamed-or-DISCARDED, which ate the entire page of any app that ends its bootstrap with a plain nested ob_end_flush() (CodeIgniter 4's Boot::bootWeb() → 200 with a 0-byte body). Above the framework's capture floor we now keep native semantics; at the floor we keep the historical streaming behaviour (flush() + close the re-opened buffer) so legacy "flush everything to the client" callers still work.

ob_implicit_flush()

Apache mod_php ob_implicit_flush() compatibility shim.

ob_implicit_flush([bool|int $enable = true ]) : void

Toggles implicit flush on/off under mod_php. ZealPHP buffers per request by default; this call is accepted as a no-op rather than crashing legacy code.

Parameters
$enable : bool|int = true

phpinfo()

mod_php-parity phpinfo(): render a self-contained HTML document instead of the CLI SAPI's plain-text dump. Matches the native signature — echoes output and returns true. Wired via uopz in App::__construct(); the renderer lives in \ZealPHP\Diagnostics\PhpInfo.

phpinfo([int $flags = INFO_ALL ]) : bool
Parameters
$flags : int = INFO_ALL

INFO_* bitmask.

Return values
bool

php_sapi_name()

mod_php-parity php_sapi_name(): under the CLI SAPI this natively returns "cli", which legacy apps branch on to disable web-only behavior. When an app opts in via App::sapiName('apache2handler') (or 'fpm-fcgi'), this returns the configured value so such code takes its web path. Default (App::$sapi_name === null) returns the real PHP_SAPI — zero behavior change unless explicitly configured.

php_sapi_name() : string

Note: the PHP_SAPI constant cannot be redefined (uopz_redefine refuses it), so code reading the constant directly still sees "cli". Documented limitation.

Return values
string

filter_input()

mod_php-parity filter_input(): native filter_input() reads PHP's internal SAPI request tables, which OpenSwoole never populates (so it returns null under CLI).

filter_input(int $type, string $var_name[, int $filter = FILTER_DEFAULT ][, array<string, mixed>|int $options = 0 ]) : mixed

This resolves the value from RequestContext ($g) and applies the requested filter.

Parameters
$type : int
$var_name : string
$filter : int = FILTER_DEFAULT
$options : array<string, mixed>|int = 0

filter_input_array()

mod_php-parity filter_input_array(): the array counterpart of filter_input().

filter_input_array(int $type[, array<string, mixed>|int $options = FILTER_DEFAULT ][, bool $add_empty = true ]) : array<string, mixed>
Parameters
$type : int
$options : array<string, mixed>|int = FILTER_DEFAULT
$add_empty : bool = true
Return values
array<string, mixed>

header_register_callback()

mod_php-parity header_register_callback(): native PHP fires the callback when the SAPI is about to send headers — which never happens the normal way under OpenSwoole. ZealPHP stores it per-request (coroutine-safe, in $g->memo) and invokes it once just before the buffered response headers are flushed, so header() calls inside the callback still land. Last registration wins (matches native, which keeps a single callback). Returns false if there's no request context (e.g. called outside a request).

header_register_callback(callable $callback) : bool

Scope note: fires for buffered responses (the common case). Streaming / SSE paths flush headers eagerly and are intentionally excluded, consistent with the framework's buffered-vs-streaming split (e.g. Range/ETag middleware).

Parameters
$callback : callable
Return values
bool

error_log()

mod_php-parity error_log(): under the CLI SAPI native error_log() writes to stderr / the php.ini error_log path. ZealPHP routes message_type 0 (system logger) and 4 (SAPI logger) into the framework's async log (debug.log, or stderr if logging is disabled) so legacy error_log() calls land where the rest of the app's diagnostics go — the "we have elog for error_log" contract.

error_log(string $message[, int $message_type = 0 ][, string|null $destination = null ][, string|null $additional_headers = null ]) : bool
  • type 3 (append to file): honored verbatim — explicit destination intent.
    • type 1 (email): unsupported under the coroutine runtime; logged + false.
    • type 0 / 4: routed to log_write() (debug.log → stderr fallback).

Always lands somewhere (never silently dropped), unlike elog() which gates on debug logging; that's why this routes through log_write() directly.

Parameters
$message : string
$message_type : int = 0
$destination : string|null = null
$additional_headers : string|null = null
Return values
bool

apache_request_headers()

Apache mod_php getallheaders() / apache_request_headers() — return all inbound request headers with canonical (Hyphen-Capitalized) case.

apache_request_headers() : array<string, string>
Return values
array<string, string>

getallheaders()

Alias for apache_request_headers() — return all inbound request headers.

getallheaders() : array<string, string>
Return values
array<string, string>

apache_response_headers()

Apache mod_php apache_response_headers() — return currently queued outbound headers.

apache_response_headers() : array<string, string>
Return values
array<string, string>

apache_setenv()

Apache mod_php per-request env table setter (apache_setenv()).

apache_setenv(string $variable, string $value[, bool $walk_to_top = false ]) : bool

Backed by Legacy\ApacheContext on G; lifetime = one request. Lazy — only allocated if legacy code calls apache_setenv()/apache_getenv()/apache_note(). The $walk_to_top flag is accepted for API compatibility but has no effect.

Parameters
$variable : string
$value : string
$walk_to_top : bool = false
Return values
bool

apache_getenv()

Apache mod_php per-request env table getter (apache_getenv()).

apache_getenv(string $variable[, bool $walk_to_top = false ]) : string|false

Returns false when no Apache context has been initialised or the variable is not set. The $walk_to_top flag is accepted for API compatibility but has no effect.

Parameters
$variable : string
$walk_to_top : bool = false
Return values
string|false

apache_note()

Apache mod_php apache_note() — per-request note table. Returns previous value.

apache_note(string $note_name[, string|null $note_value = null ]) : string

When $note_value is null, acts as a getter only. Setting a value lazily initialises the ApacheContext if needed.

Parameters
$note_name : string
$note_value : string|null = null
Return values
string

virtual()

Apache mod_php virtual() — performs an internal subrequest.

virtual(string $uri) : bool

Not supported in ZealPHP's single-process model; logs once via elog() and returns false rather than crashing legacy code.

Parameters
$uri : string
Return values
bool

set_time_limit()

set_time_limit() compatibility shim.

set_time_limit(int $seconds) : bool

OpenSwoole has its own coroutine/worker timeouts and the native PHP execution-time limit is irrelevant here. Treated as no-op success.

Parameters
$seconds : int
Return values
bool

ignore_user_abort()

ignore_user_abort() compatibility shim (uopz override).

ignore_user_abort([bool|null $enable = null ]) : int

Apache mod_php controls whether the script keeps running after the client disconnects. The state is tracked in G; with OpenSwoole the coroutine continues regardless, but we honor the API contract. When called with no argument, returns the current setting without changing it.

Parameters
$enable : bool|null = null
Return values
int

connection_status()

Return the connection status for the current request.

connection_status() : int

Returns 1 (CONNECTION_ABORTED) when the underlying openswoole_response is no longer writable, 0 (CONNECTION_NORMAL) otherwise.

Return values
int

connection_aborted()

Return 1 when the client connection has been aborted, 0 otherwise.

connection_aborted() : int

Equivalent to connection_status() === 1.

Return values
int

output_add_rewrite_var()

Apache's URL-rewrite output handler — not used in ZealPHP. No-op returning false.

output_add_rewrite_var(string $name, string $value) : bool
Parameters
$name : string
$value : string
Return values
bool

output_reset_rewrite_vars()

Apache's URL-rewrite output handler reset — not used in ZealPHP. No-op returning true.

output_reset_rewrite_vars() : bool
Return values
bool

is_uploaded_file()

is_uploaded_file() compatibility shim (uopz override).

is_uploaded_file(string|null $filename) : bool

Verifies that $filename is one of the temp paths registered in this request's $_FILES (via $g->files). Rejects forged paths from user input.

Parameters
$filename : string|null
Return values
bool

_zealphp_tmp_name_matches()

Recursively test whether $filename is one of the temp-path leaves in a field-major $_FILES[...]['tmp_name'] value (scalar or nested array).

_zealphp_tmp_name_matches(mixed $tmp, string $filename) : bool
Parameters
$tmp : mixed

Scalar tmp path or an (possibly nested) array of them.

$filename : string
Return values
bool

move_uploaded_file()

move_uploaded_file() compatibility shim (uopz override).

move_uploaded_file(string|null $from, string|null $to) : bool

Equivalent to Apache+mod_php behaviour, gated by is_uploaded_file() and falling back to copy()+unlink() across filesystems when rename() fails.

Parameters
$from : string|null
$to : string|null
Return values
bool

set_error_handler()

Per-request set_error_handler() (uopz override).

set_error_handler(callable|null $callback[, int $error_levels = E_ALL ]) : callable|null

The native PHP error handler is installed at boot and delegates to G's per-coroutine stack. This override records the user-space registration in $g->error_handlers_stack without touching the engine handler. Passing null pops the most recently registered handler (matches native behaviour).

Parameters
$callback : callable|null
$error_levels : int = E_ALL
Return values
callable|null

restore_error_handler()

Pop the most recently registered per-request error handler.

restore_error_handler() : bool

Mirrors the native restore_error_handler() contract; always returns true.

Return values
bool

set_exception_handler()

Per-request set_exception_handler() (uopz override).

set_exception_handler(callable|null $callback) : callable|null

Stores the handler in $g->exception_handlers_stack. Passing null pops the most recently registered handler. Returns the previously active handler (or null when none was set).

Parameters
$callback : callable|null
Return values
callable|null

restore_exception_handler()

Pop the most recently registered per-request exception handler.

restore_exception_handler() : bool

Mirrors the native restore_exception_handler() contract; always returns true.

Return values
bool

register_shutdown_function()

Per-request shutdown function (uopz override of register_shutdown_function()).

register_shutdown_function(callable $callback, mixed ...$args) : void

Fires after the route handler returns and before the PSR response is emitted, so the callback can still call echo/header()/http_response_code() and have those land in the response. Multiple callbacks are supported and called in registration order.

Parameters
$callback : callable
$args : mixed

error_reporting()

Per-coroutine error_reporting() (uopz override).

error_reporting([int|null $error_level = null ]) : int

When called without an argument, returns the current reporting level for this coroutine (falling back to the level captured at App boot via App::$initial_error_reporting). When called with a level, stores it in $g->error_reporting_level and returns the previous level.

Parameters
$error_level : int|null = null
Return values
int
On this page