Skip to content

HTTP Server

Every PAM web application, whatever framework it uses, ends in the same place: a PHP callable registered with the runtime’s HTTP server. PAM owns the socket in Rust (HTTP/1.1, HTTP/2, and HTTP/3 over TLS), parses the request, and calls your handler inside a PHP Fiber of a worker that stays in memory between requests.

Most applications never touch this layer directly. Nimbus, the HTTP framework that pam init --template api installs, builds on it and calls Pam\Http\Server for you. Read this page when you want to:

  • write a tiny service or a health endpoint without a framework;
  • understand what $request and $response are inside Nimbus handlers, since they are the same classes;
  • tune the listener: body limits, timeouts, CORS, trusted proxies, TLS, metrics, and the response cache.

A PAM server is a PHP script that calls listen(). Create server.php:

server.php
<?php
declare(strict_types=1);
use Pam\Http\Request;
use Pam\Http\Response;
use Pam\Http\Server;
$visits = 0; // Lives as long as the worker, not the request.
Server::create(function (Request $request, Response $response) use (&$visits): Response {
$visits++;
return match ([$request->method, $request->path]) {
['GET', '/'] => $response->json(['message' => 'Hello from PAM', 'visits' => $visits]),
['POST', '/echo'] => $response->json(['received' => $request->json()], 201),
default => $response->status(404)->send('Not Found'),
};
})->listen((int) (getenv('PAM_PORT') ?: 3000));

Run it with the PAM CLI. pam dev restarts the server when a file changes; pam server.php runs it once:

Terminal window
pam dev server.php
Terminal window
$ curl http://127.0.0.1:3000/
{"message":"Hello from PAM","visits":1}
$ curl http://127.0.0.1:3000/
{"message":"Hello from PAM","visits":2}
$ curl -X POST http://127.0.0.1:3000/echo -d '{"name":"Alice"}'
{"received":{"name":"Alice"}}

The $visits counter shows the most important property of PAM: the script runs once per worker, and the handler runs for every request. Anything defined outside the handler survives between requests. That is what makes PAM fast, and it is also the main thing to keep in mind when you write code for it. See Request Lifecycle and Memory & State.

Pam\Http\Server offers two constructors. Only one HTTP handler can be registered per worker; registering a second one throws a LogicException.

The handler receives a Pam\Http\Request and a Pam\Http\Response. This is the style Nimbus uses.

Server::create(function (Request $request, Response $response): Response {
return $response->json(['path' => $request->path]);
})->listen(3000);

In both styles the handler may return:

  • the Response (the usual case);
  • a string, number, or boolean, which becomes the body when the response is still empty;
  • null, in which case whatever was written to the $response object is sent.

Pam\Http\Request is an immutable value object built by the runtime for each request.

Member Returns Notes
$request->method string Upper-case method, such as GET.
$request->path string Path without the query string, such as /users/7.
getQuery(string $key, mixed $default = null) mixed One query string value.
query() array All query string values.
getHeader(string $name, ?string $default = null) ?string Case-insensitive; repeated headers are joined with , .
headers() array Lower-case header names mapped to lists of values.
body() string The raw body.
json() mixed json_decode() of the body as arrays; throws JsonException when the body is not valid JSON.
route(string $key, ?string $default = null) ?string A route parameter set by a router.
routeParameters() array All route parameters.
withRouteParameters(array $parameters) Request A copy with route parameters, used by routers.
Server::create(function (Request $request, Response $response): Response {
$page = (int) $request->getQuery('page', 1);
$token = $request->getHeader('authorization');
return $response->json(['page' => $page, 'authenticated' => $token !== null]);
})->listen(3000);

Cookies, form fields and uploaded files are not methods of the request object; read them from $_COOKIE, $_POST and $_FILES, which PAM fills for every request (see Superglobals). Nimbus adds helpers for them, described in Requests.

Pam\Http\Response is a mutable builder. Every setter returns the same instance, so calls chain.

Method Description
status(int $statusCode) Sets the status (100-599).
header(string $name, string $value) Sets a header, replacing previous values.
addHeader(string $name, string $value) Appends another value for the header.
cookie(string $name, string $value = '', array $options = []) Adds a Set-Cookie header.
send(string|int|float|bool|null $body) Sets the body. Adds text/plain; charset=utf-8 unless a content type is set (and the status is not 204 or 304).
json(mixed $data, int $statusCode = 200) Encodes JSON (unescaped Unicode) with application/json; charset=utf-8.
stream(iterable $chunks, string $contentType = 'application/octet-stream') Streams each chunk to the client.
streamOutput(callable $producer, int $chunkBytes = 65536) Streams everything the producer echoes.
writeChunk(string $chunk) Writes one chunk of a streamed response.
sse(iterable $events) Streams Server-Sent Events.
isEmpty() Whether the body is still empty.

Header names are validated and lower-cased; values containing CR, LF or NUL bytes throw InvalidArgumentException, so header injection is not possible through this API.

cookie() accepts the options expires, max-age, domain, path, samesite, secure and httponly (case-insensitive). true writes a bare flag, false and null omit the attribute, and any other key throws.

return $response
->cookie('theme', 'dark', [
'max-age' => 3600,
'path' => '/',
'httponly' => true,
'samesite' => 'Lax',
])
->json(['ok' => true]);
set-cookie: theme=dark; Max-Age=3600; Path=/; HttpOnly; SameSite=Lax

Streamed responses are sent with chunked transfer encoding. Each chunk is handed to the Rust transport through a bounded queue; when the client reads slowly, the request Fiber suspends instead of buffering the whole response in PHP memory.

$response->stream((function (): Generator {
foreach (['one', 'two', 'three'] as $word) {
yield $word . "\n";
}
})(), 'text/plain; charset=utf-8');

streamOutput() captures PHP output, which is handy for templates and CSV exports:

return $response
->header('content-type', 'text/csv')
->streamOutput(function (): void {
echo "id,name\n";
foreach ([[1, 'Alice'], [2, 'Bob']] as [$id, $name]) {
echo "{$id},{$name}\n";
}
});

sse() formats each event as a data: line (arrays are JSON-encoded) and sets text/event-stream, cache-control: no-cache and connection: keep-alive:

return $response->sse([['tick' => 1], ['tick' => 2]]);
data: {"tick":1}
data: {"tick":2}

See Streams & SSE for long-lived streams, backpressure and client disconnects.

PAM fills the PHP superglobals for every request and clears them when the request ends, so code written for PHP-FPM keeps working:

  • $_GET, $_POST (urlencoded and multipart bodies), $_COOKIE, $_FILES and $_REQUEST;
  • $_SERVER with REQUEST_METHOD, REQUEST_URI, QUERY_STRING, SERVER_PROTOCOL, REMOTE_ADDR, REMOTE_PORT, REQUEST_SCHEME, HTTPS, HTTP_HOST, CONTENT_TYPE, CONTENT_LENGTH and one HTTP_* entry per header;
  • $_SERVER['PAM_REQUEST_ID'] and $_SERVER['PAM_TRACEPARENT'], the correlation id and W3C trace context of the request.

A few rules differ from a naive CGI mapping, on purpose:

  • Headers with an underscore stay out of $_SERVER. X-Forwarded_For could otherwise overwrite the HTTP_X_FORWARDED_FOR set by your proxy. The header is still available through $request->getHeader().
  • REMOTE_ADDR respects trustedProxies. Behind a trusted proxy it is the rightmost X-Forwarded-For entry that is not itself a trusted proxy, never the leftmost entry that the client controls.
  • The client’s X-Request-Id is only a label. It is echoed in the response, the access log and PAM_REQUEST_ID, but the runtime always generates its own internal dispatch key.
Terminal window
$ curl -H 'user-agent: curl-docs' -H 'X-Forwarded_For: 6.6.6.6' -H 'x-request-id: my-trace-1' \
http://127.0.0.1:3000/server
{"remote":"127.0.0.1","requestId":"my-trace-1","ua":"curl-docs","underscore":null}

The third argument of listen() configures the transport. Unknown keys are ignored, and invalid values throw during boot, so a typo in a number fails fast.

index.php
$app->listen((int) (getenv('PAM_PORT') ?: 3000), '0.0.0.0', [
'maxBodyBytes' => 8 * 1024 * 1024,
'requestTimeoutMs' => 15_000,
'corsOrigins' => ['https://app.example.com'],
'trustedProxies' => ['10.0.0.0/8'],
'accessLog' => true,
]);

Nimbus’ App::listen() takes the same options and passes them through unchanged.

Option Default Description
maxBodyBytes 2097152 (2 MiB) Largest request body; larger requests get 413.
maxHeaderBytes 32768 Largest header section.
maxHeaders 100 Maximum number of request headers.
headerReadTimeoutMs 10000 Time allowed to receive the headers (slowloris protection).
bodyReadTimeoutMs 30000 Time allowed to receive the body.
requestTimeoutMs 30000 Request deadline; a request past it gets 504 and the worker is recycled.
maxConcurrentRequests 4096 Requests a worker keeps in flight at once.
maxConnections 0 Connections per worker; 0 means the open file limit minus 256 descriptors kept for PHP. Past it the worker stops accepting until a connection closes.
maxInflightBodyBytes a quarter of memory_limit Request bodies PHP may hold at once in a worker; 0 disables the budget. A request over it waits up to requestTimeoutMs, then gets 503 with Retry-After. PAM_MAX_INFLIGHT_BODY_BYTES overrides it.
phpExecutorQueueCapacity 1024 Requests queued for the PHP thread.
rateLimitPerSecond 0 (off) Per-client token bucket in the transport; tracks at most 65,536 clients per worker.

Multipart uploads follow PHP’s own settings (file_uploads, upload_max_filesize, post_max_size, max_file_uploads, upload_tmp_dir). A body with more parts than max_multipart_body_parts (by default max_input_vars + max_file_uploads) is rejected with 400.

Option Default Description
maxResponseBytes 268435456 (256 MiB) Largest complete response.
maxResponseChunkBytes 1048576 (1 MiB) Largest single chunk; cannot exceed maxResponseBytes.
responseStreamQueueCapacity 16 Chunks buffered between PHP and the socket before the Fiber waits.
Option Default Description
corsOrigins [] Origins allowed by CORS. The transport answers preflight requests itself.
trustedProxies [] Proxy addresses or CIDR ranges allowed to set X-Forwarded-For. PAM_TRUSTED_PROXIES (comma separated) adds to it. * trusts every peer and logs a warning.
exposeErrors false Send exception messages in 500 responses and leave PHP’s display_errors alone. Development only.
accessLog false Write one JSON line per request to stderr.
accessLogSampleRate 1 Log one request in N. Server errors are always logged.
telemetryHeaders false Add x-request-id, traceparent and server-timing headers to responses.
Option Default Description
tlsCert, tlsKey null PEM certificate and key paths. Enables HTTPS and HTTP/2 over ALPN.
http3 true Serve HTTP/3 (QUIC) when TLS is configured; requires UDP on the same port.
http2MaxConcurrentStreams 256 Streams per HTTP/2 connection.
http2StreamWindowBytes 1048576 HTTP/2 stream flow-control window.
http2ConnectionWindowBytes 4194304 HTTP/2 connection flow-control window.

Certificates are read when a worker starts. Under pam start, send SIGHUP to the master after renewing the files and a new worker generation loads them without dropping requests.

Option Default Description
metricsPath /metrics Prometheus endpoint of the worker.
metricsToken null Require Authorization: Bearer <token>. Also PAM_METRICS_TOKEN.
metricsPublic false Serve metrics to any peer without a token. Also PAM_METRICS_PUBLIC=1.
routeMetrics false Per-route metrics, bounded by routeMetricsMaxEntries (256).

By default only loopback peers without forwarding headers can read metricsPath; other peers reach your application’s own route with that path.

The listener also accepts WebSocket options (websocket*, see WebSockets), an edge response cache (responseCache*, see Shared Memory & Caching) and garbage-collection and leak-detection tuning (gcCollectCyclesEvery, gcMemCachesEvery, leakDetectionSampleRate, leakThresholdBytes, see Memory & State). The Configuration Reference lists every key.

Set corsOrigins on the listener. The Rust transport then answers every preflight request (OPTIONS with Access-Control-Request-Method) with 204 before PHP runs, and adds access-control-allow-origin to responses for allowed origins:

Terminal window
$ curl -i -X OPTIONS http://127.0.0.1:3000/api/products \
-H 'origin: https://app.example.com' -H 'access-control-request-method: POST'
HTTP/1.1 204 No Content
access-control-allow-origin: https://app.example.com
access-control-allow-methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
access-control-allow-headers: authorization, content-type, x-request-id, traceparent
vary: Origin

When a handler throws, the runtime logs the exception (class, message, file and line) as JSON on stderr and answers a generic 500:

{"error":"Internal Server Error","message":"The request failed. Use the request ID to inspect server logs."}

With exposeErrors: true the message field carries the exception message instead. Keep it off in production: messages often contain SQL, paths or secrets.

In server mode PAM also turns off display_errors and turns on log_errors unless exposeErrors is set, and expose_php defaults to off, so PHP warnings never leak into response bodies. If a client disconnects mid-request, the request Fiber is cancelled and the runtime records status 499.

Frameworks usually catch exceptions before the runtime does. Nimbus renders them as Problem Details; see Error Handling.

The runtime can also serve a PSR-15 request handler. With Nimbus, pass any Psr\Http\Server\RequestHandlerInterface (or callable) to handler() and register PSR-15 middleware with middleware():

index.php
$app = new Nimbus\App();
$app->handler($psrHandler); // Psr\Http\Server\RequestHandlerInterface
$app->middleware($psrMiddleware); // Psr\Http\Server\MiddlewareInterface
$app->listen(3000);

The runtime builds a PSR-7 ServerRequest from the request and converts the PSR-7 response back. This path needs the PSR-7 and PSR-15 implementation in pushinbr/pam-http-psr:

Terminal window
pam composer require pushinbr/pam-http-psr

See PSR interoperability.

pam dev is for development only. In production, run the same entry point under the supervised cluster:

Terminal window
pam start index.php --workers 4

Each worker is a separate process with its own copy of your application; the transport shares the port between them. See Clustering and Production.