In this tutorial, we are going to show you how to send a “404 Not Found” header using PHP.
This can be especially useful in cases when you need to display a 404 message if a particular database record does not exist.
By sending a 404 HTTP status code to the client, we can tell search engines and other crawlers that the resource does not exist.
To send a 404 to the client, we can use PHP’s http_response_code function like so.
//Send 404 response to client. http_response_code(404) //Include custom 404.php message include 'error/404.php'; //Kill the script. exit;
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.
//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 exit;
In the code above, we.
- Send the response code to the client.
- We include 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.
- We then terminated the PHP script by calling the exit statement.
If you run one of the code samples above and check the response in your browser’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 a 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 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.
In cases like this, we may need to manually send a 404 Not Found header.
Why isn’t PHP showing the same 404 message as my web server?
You might notice that your web server does not serve its 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 404 message.
For example, with Apache, you can specify the path of a custom error message by using the ErrorDocument directive.
ErrorDocument 404 /errors/404.php
The Nginx web server also allows you to configure custom error messages.