How can you ensure that a non-existing page redirects to the default main page in PHP?
When a user tries to access a non-existing page on a website, it is common practice to redirect them to the default main page to prevent errors or confusion. This can be achieved by using PHP to check if the requested page exists, and if not, redirecting the user to the main page.
<?php
$page = isset($_GET['page']) ? $_GET['page'] : 'main'; // Check if a page is requested
$valid_pages = ['main', 'about', 'contact']; // Define valid pages
if (!in_array($page, $valid_pages)) {
header("Location: index.php?page=main"); // Redirect to main page if requested page is not valid
exit();
}
// Rest of your code here
?>
Keywords
Related Questions
- How can performance be optimized when generating 3000 links in PHP for a calendar planning system?
- How can dynamic variable naming be achieved in PHP for translation purposes?
- What are some best practices for handling directory changes in PHP FTP upload to avoid errors like the one mentioned in the thread?