How to return a 404 error
Short answer
Set the response code and end the program:
<?php
// page.php
http_response_code(404);
echo 'Page not found';
exit;A record is not found
This is the answer when the database has no record with the requested number:
<?php
// product.php
$product = null; // the result of a database query
if ($product === null) {
http_response_code(404);
require __DIR__ . '/views/404.php';
exit;
}For an API
A JSON response:
<?php
http_response_code(404);
header('Content-Type: application/json');
echo json_encode(['error' => 'Product not found']);Functions used in this recipe
- http_response_code — Sets or returns the response status code.
- header — Sends an HTTP response header.
- exit — Terminates the program.