HTTP Responses

Basics

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

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

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

// Get the status code
$response->getStatusCode();

// Set the status code
$response->setStatusCode(500);

// 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)
$response->getHeaders();

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

// Get the body (could be null)
$response->getBody();

// 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, 'http://example.com');

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(
    $response,
    new Cookie(
        name: 'token',
        value: 'abc123',
        maxAge: 3600,
        path: '/',
        domain: 'example.com',
        isSecure: true, // Defaults to true
        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;