HTTP Responses


Responses are HTTP messages that are sent by servers back to the client. They contain data like the status code, headers, and body.

use Aphiria\Net\Http\Headers;
use Aphiria\Net\Http\Response;
use Aphiria\Net\Http\StringBody;

$response = new Response(
    new Headers(),
    new StringBody('foo')

// Get the status code

// Set the status code

// Get the reason phrase
$response->getReasonPhrase(); // "OK"

// Get the protocol version
$response->getProtocolVersion(); // 1.1

// Get the headers (you can add new headers to the returned hash table)

// Set a header
$response->getHeaders()->add('Foo', 'bar');

// Get the body (could be null)

// Set the body
$response->setBody(new StringBody('foo'));

JSON Responses

Aphiria provides an easy way to create common responses. For example, to create a JSON response, use ResponseFormatter:

use Aphiria\Net\Http\Formatting\ResponseFormatter;
use Aphiria\Net\Http\Response;

$response = new Response();
(new ResponseFormatter)->writeJson($response, ['foo' => 'bar']);

This will set the contents of the response, as well as the appropriate Content-Type headers.

Redirect Responses

You can also create a redirect response:

use Aphiria\Net\Http\Formatting\ResponseFormatter;
use Aphiria\Net\Http\Response;

$response = new Response();
(new ResponseFormatter)->redirectToUri($response, '');

Setting Cookies

Cookies are headers that are automatically appended to each request from the client to the server. To set one, use ResponseFormatter:

use Aphiria\Net\Http\Formatting\ResponseFormatter;
use Aphiria\Net\Http\Headers\Cookie;

(new ResponseFormatter)->setCookie(
    new Cookie(
        name: 'token',
        value: 'abc123',
        maxAge: 3600,
        path: '/',
        domain: '',
        isSecure: true, // Defaults to false
        isHttpOnly: true, // Defaults to true
        sameSite: Cookie::SAME_SITE_LAX // Defaults to lax

Use ResponseFormatter::setCookies() to set multiple cookies at once.

Deleting Cookies

To delete a cookie on the client, call

(new ResponseFormatter)->deleteCookie($response, 'userid');

Writing Responses

Once you're ready to start sending the response back to the client, you can use ResponseWriter:

use Aphiria\Net\Http\ResponseWriter;

(new ResponseWriter)->writeResponse($response);

By default, this will write the response to the php://output stream. You can override the stream it writes to via the constructor:

$outputStream = new Stream(fopen('path/to/output', 'wb'));
(new ResponseWriter($outputStream))->writeResponse($response);

Serializing Responses

Aphiria can serialize responses per RFC 7230:

echo (string)$response;