Send 404 Not Found header with PHP.

In this tutorial, I will show you how to send a 404 Not Found header using PHP. This can be especially useful in cases when you want to throw a 404 Not Found header if a particular database resource does not exist.

To send a 404 to the client, we can use PHP’s http_response_code function like so. Note that this function is only available in PHP version 5.4 and after:

If you are using a PHP version that is older than 5.4, then you can use the header function instead:

In the code above, we:

  1. Sent the response code to the client.
  2. We included a php file that contains our custom “404 Not Found” error. This is not mandatory, so feel free to remove this if you want to.
  3. We terminated the PHP script by calling exit.

If you run one of the code samples above and check the response in Chrome’s developer tools, then you will see something like this:

Note the Status Code segment of the server’s HTTP response.

When should I use this?

In most cases, your web server will automatically handle 404 errors if an image or a particular resource does not exist. However, what happens if your script is dynamic and it selects data from your database? What if you have a dynamic page such as users.php?id=234 and the user 234 does not exist? The file users.php will exist, so your web server will send back a status 200 OK, regardless of whether a user with the ID 234 exists or not. It is in cases like this that we can check to see if the database resource exists and manually send a 404 Not Found header if it doesn’t.

Why isn’t PHP showing the same 404 message as my web server?

You might have noticed that the web server does not serve it’s default 404 Not Found error message when you manually send the header with PHP.

404 Not Found

The default message that Apache displays whenever a resource could not be found.

This is because, as far the web server is concerned, the file does exist and it has already done it’s job. One solution to this problem is to make sure that PHP and your web server display the exact same error message whenever a 404 error occurs. For example, with Apache, you can specify the path of a custom error message by using theĀ ErrorDocument directive like so:

Hopefully, you found this tutorial to be useful!