Skip to content

Core\Response::setStatus

Core\Response::setStatus(uint $code): voidCore\Response::setStatus(
    uint $code,
): void

Sets the HTTP status of the response. The status is a number that tells the client how the request went: 200 means it worked, 201 means something was created, 404 means the page does not exist, and 500 means the server had an error. If your program does not set a status, it is 200.

setStatus does not write a body. You can use it together with echo or with a body method such as Core\Response::sendJson. If you call it more than once, the last call sets the status. If the request fails with an error, the status is 500.

A status is between 100 and 599. For any other number, setStatus throws a LogicError and the status does not change.

The examples show a page that does not exist, a number that is not a status, and an API that checks its input.

Parameters

  • $codeuintThe status code, from 100 to 599.

Return value

Returns void. Nothing. If you call it more than once, the last call sets the status. If the request fails with an error, the status is 500.

Errors

  • LogicError$code is less than 100 or greater than 599. The status does not change.

Examples

A page that does not exist

<?nvs
// Shows how to answer with status 404 when a visitor asks for a page that does not exist.
// The path comes from the visitor, so it is a `tainted string`.
tainted string $path = Core\Request::path();
if ($path == '/about' || $path == '/contact') {
Core\Response::sendText('This is the page ' . $path . "\n");
} else {
// The path is `/prices`, so the status is 404 and this text is the body.
Core\Response::setStatus(404);
Core\Response::sendText('Status 404: there is no page ' . $path . "\n");
}
Output
Status 404: there is no page /prices

A number that is not a status

<?nvs
// Shows what happens when a number is not an HTTP status.
// A status is between 100 and 599. 600 is not, so `setStatus` throws a `LogicError`.
// The status does not change, so it is still 200.
try {
Core\Response::setStatus(600);
} catch (LogicError $error) {
Core\Response::sendText('Status 200. The error was: ' . $error->message . "\n");
}
Output
Status 200. The error was: Core\Response::setStatus(): `600` is not an HTTP status — a status is three digits naming one of five classes, so it is between 100 and 599

An api that checks its input

<?nvs
// Shows an API that answers with status 422 when a required value is missing.
// The request has no `email` value, so `query` returns `null`.
?tainted string $email = Core\Request::queryParameter('email');
if ($email == null) {
// 422 tells the client that the request is wrong and must be changed.
Core\Response::setStatus(422);
Core\Response::sendJson({ status: 422, error: 'The value email is required.' });
} else {
Core\Response::setStatus(201);
Core\Response::sendJson({ status: 201, email: $email });
}
Output
{"error":"The value email is required.","status":422}