Http
PSR HTTP Message implementations and node-like http.Server implementation
Install / Use
/learn @phly/HttpREADME
phly/http
:warning: Archived 2025-08-17
Abandoned! Or, rather, rebranded!
phly/http has moved to the zendframework organization as zend-diactoros (Diactoros, literally "the messenger," an epithet for Hermes).
Please use that package instead, and contribute issues and pull requests against it I have closed issues and pull requests against phly/http at this time.
phly/http is a PHP package containing implementations of the accepted PSR-7 HTTP message interfaces, as well as a "server" implementation similar to node's http.Server.
This package exists:
- to provide a proof-of-concept of the proposed PSR HTTP message interfaces with relation to server-side applications.
- to provide a node-like paradigm for PHP front controllers.
- to provide a common methodology for marshaling a request from the server environment.
Installation and Requirements
Install this library using composer:
$ composer require phly/http
phly/http has the following dependencies (which are managed by Composer):
psr/http-message, which defines interfaces for HTTP messages, including requests and responses.phly/httpprovides implementations of each of these.
Usage
Usage will differ based on whether you are writing an HTTP client, or a server-side application.
For HTTP client purposes, you will create and populate a Request instance, and the client should return a Response instance.
For server-side applications, you will create a ServerRequest instance, and populate and return a Response instance.
HTTP Clients
A client will send a request, and return a response. As a developer, you will create and populate the request, and then introspect the response. Both requests and responses are immutable; if you make changes -- e.g., by calling setter methods -- you must capture the return value, as it is a new instance.
// Create a request
$request = (new Phly\Http\Request())
->withUri(new Phly\Http\Uri('http://example.com'))
->withMethod('PATCH')
->withAddedHeader('Authorization', 'Bearer ' . $token)
->withAddedHeader('Content-Type', 'application/json');
// OR:
$request = new Phly\Http\Request(
'http://example.com',
'PATCH',
'php://memory',
[
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
]
);
// If you want to set a non-origin-form request target, set the
// request-target explicitly:
$request = $request->withRequestTarget((string) $uri)); // absolute-form
$request = $request->withRequestTarget($uri->getAuthority()); // authority-form
$request = $request->withRequestTarget('*'); // asterisk-form
// Once you have the instance:
$request->getBody()->write(json_encode($data));
$response = $client->send($request);
printf("Response status: %d (%s)\n", $response->getStatusCode(), $response->getReasonPhrase());
printf("Headers:\n");
foreach ($response->getHeaders() as $header => $values) {
printf("%s: %s\n", $header, implode(', ', $values));
}
printf("Message:\n%s\n", $response->getBody());
(Note: phly/http does NOT ship with a client implementation; the above is just an illustration of a possible implementation.)
Server-Side Applications
Server-side applications will need to marshal the incoming request based on superglobals, and will then populate and send a response.
Marshaling an incoming request
PHP contains a plethora of information about the incoming request, and keeps that information in a variety of locations. Phly\Http\ServerRequestFactory::fromGlobals() can simplify marshaling that information into a request instance.
You can call the factory method with or without the following arguments, in the following order:
$server, typically$_SERVER$query, typically$_GET$body, typically$_POST$cookies, typically$_COOKIE$files, typically$_FILES
The method will then return a Phly\Http\ServerRequest instance. If any argument is omitted, the associated superglobal will be used.
$request = Phly\Http\ServerRequestFactory::fromGlobals(
$_SERVER,
$_GET,
$_POST,
$_COOKIE,
$_FILES
);
Manipulating the response
Use the response object to add headers and provide content for the response. Writing to the body does not create a state change in the response, so it can be done without capturing the return value. Manipulating headers does, however.
$response = new Phly\Http\Response();
// Write to the response body:
$response->getBody()->write("some content\n");
// Multiple calls to write() append:
$response->getBody()->write("more content\n"); // now "some content\nmore content\n"
// Add headers
// Note: headers do not need to be added before data is written to the body!
$response = $response
->withHeader('Content-Type', 'text/plain')
->withAddedHeader('X-Show-Something', 'something');
"Serving" an application
Phly\Http\Server mimics a portion of the API of node's http.Server class. It invokes a callback, passing it an ServerRequest, an Response, and optionally a callback to use for incomplete/unhandled requests.
You can create a server in one of three ways:
// Direct instantiation, with a callback handler, request, and response
$server = new Phly\Http\Server(
function ($request, $response, $done) {
$response->getBody()->write("Hello world!");
},
$request,
$response
);
// Using the createServer factory, providing it with the various superglobals:
$server = Phly\Http\Server::createServer(
function ($request, $response, $done) {
$response->getBody()->write("Hello world!");
},
$_SERVER,
$_GET,
$_POST,
$_COOKIE,
$_FILES
);
// Using the createServerFromRequest factory, and providing it a request:
$server = Phly\Http\Server::createServerfromRequest(
function ($request, $response, $done) {
$response->getBody()->write("Hello world!");
},
$request
);
Server callbacks can expect up to three arguments, in the following order:
$request- the request object$response- the response object$done- an optional callback to call when complete
Once you have your server instance, you must instruct it to listen:
$server->listen();
At this time, you can optionally provide a callback to listen(); this will be passed to the handler as the third argument ($done):
$server->listen(function ($request, $response, $error = null) {
if (! $error) {
return;
}
// do something with the error...
});
Typically, the listen callback will be an error handler, and can expect to
receive the request, response, and error as its arguments (though the error may
be null).
API
Request Message
Phly\Http\Request implements Psr\Http\Message\RequestInterface, and is intended for client-side requests. It includes the following methods:
class Request
{
public function __construct(
$uri = null,
$method = null,
$body = 'php://memory',
array $headers = []
);
// See psr/http-message's RequestInterface for other methods
}
Requests are immutable. Any methods that would change state -- those prefixed with with and without -- all return a new instance with the changes requested.
ServerRequest Message
For server-side applications, Phly\Http\ServerRequest implements Psr\Http\Message\ServerRequestInterface, which provides access to the elements of an HTTP request, as well as uniform access to the various elements of incoming data. The methods included are:
class ServerRequest
{
public function __construct(
array $serverParams = [],
array $fileParams = [],
$uri = null,
$method = null,
$body = 'php://input',
array $headers = []
);
// See psr/http-message's ServerRequestInterface for other methods.
}
The ServerRequest is immutable. Any methods that would change state -- those prefixed with with and without -- all return a new instance with the changes requested. Server parameters are considered completely immutable, however, as they cannot be recalculated, and, rather, is a source for other values.
Response Message
Phly\Http\Response provides an implementation of Psr\Http\Message\ResponseInterface, an object to be used to aggregate response information for both HTTP clients and server-side applications, including headers and message body content. It includes the following:
class Response
{
public function __construct(
$body = 'php://memory',
$statusCode = 200,
array $headers = []
);
// See psr/http-message's ResponseInterface for other methods
}
Like the Request and ServerRequest, responses are immutable. Any methods that would change state -- those prefixed with with and without -- all return a new instance with the changes requested.
ServerRequestFactory
This static class can be used to marshal a ServerRequest instance from the PHP environment. The primary entry point is Phly\Http\ServerRequestFactory::fromGlobals(array $server, array $query, array $body, array $cookies, array $files). This method will create a new ServerRequest instance with th
Related Skills
node-connect
347.9kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
108.7kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
347.9kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
qqbot-media
347.9kQQBot 富媒体收发能力。使用 <qqmedia> 标签,系统根据文件扩展名自动识别类型(图片/语音/视频/文件)。



