How can PHP be used to redirect users to a custom error page when a wrong page is accessed?

When a user accesses a wrong page on a website, PHP can be used to redirect them to a custom error page. This can be achieved by checking the requested page against a list of valid pages and if it doesn't match, redirecting the user to the error page using the header() function.

<?php
$valid_pages = array("home", "about", "contact");

$page = isset($_GET['page']) ? $_GET['page'] : 'home';

if (!in_array($page, $valid_pages)) {
    header("Location: error_page.php");
    exit();
}

// Rest of the code to display the requested page
?>