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
?>