How can PHP developers ensure that non-existent pages return a 404 error instead of redirecting to the homepage?
To ensure that non-existent pages return a 404 error instead of redirecting to the homepage, PHP developers can use the header() function to set the HTTP response code to 404. This will inform the browser that the requested page was not found. Additionally, developers can customize the error page to display a user-friendly message to the visitors.
<?php
if (!file_exists($_SERVER['DOCUMENT_ROOT'] . $_SERVER['REQUEST_URI'])) {
http_response_code(404);
include('404-error-page.php'); // Include a custom error page
exit();
}
?>
Keywords
Related Questions
- Are there specific structures that classes must adhere to in order to be considered object-oriented in PHP?
- What best practices should PHP beginners follow when working with tabular data outputs in their code?
- How does the concept of layouting and sanitizing play a role in the difference between using a template engine and a regular PHP file for rendering content?