Saturday, October 22, 2011

How to create a 404 error page in PHP

How can we display the 404 (Not Found) error in PHP?

We need two things to do that. First, we have to let the visitor's browser know that the requested page does not exist. Second, we have to show the error message to the visitor.

The 'machine part' of the 404 error page


The browser (or the bot of the search engine, or any other WWW client) learns about the nonexistent page from the page headers. Header information must be the first thing sent to the browser, therefore no echo, print or similar commands can be executed before that. The PHP code is as follows:

<?php
header("HTTP/1.0 404 Not Found");


The 'human part' of the 404 error page


The message for the visitor is presented using the regular HTML code, as the 404 error page is just a usual HTML document. The only difference is in the headers, as described earlier. Similar PHP code could be used:

<?php
echo "<html>
<head>
<title>Error 404 - Page Not Found</title>
</head>
<body>
<h1>Error 404</h1>
<p>The page was not found.</p>
</body>
</html>";

No comments:

Post a Comment