404 Not Found header with PHP

404 Not Found header with PHP

his 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:

//Send 404 response to client.
//Include custom 404.php message
include 'error/404.php';
//Kill the script.

//Use header function to send a 404
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404);
//Include custom message.
include 'errors/404.php';
//End the script

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:

Request URL:http://localhost/test.php
Request Method:GET
Status Code:404 Not Found
Remote Address:[::1]:80
Referrer Policy:no-referrer-when-downgrade

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.

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:

ErrorDocument 404 /errors/404.php


Schedule a free consultation

Ask questions, discuss details and decide if it's a fit.

Handcrafted by me © 2021

Made with with Django & Python