Are there any best practices to follow when using the include function in PHP for page navigation?

When using the include function in PHP for page navigation, it is important to sanitize user input to prevent any potential security vulnerabilities such as directory traversal attacks. One best practice is to use absolute paths instead of relative paths when including files to ensure that the correct file is included regardless of the current working directory.

<?php
// Sanitize user input for page navigation
$page = isset($_GET['page']) ? $_GET['page'] : 'home';

// Define allowed pages
$allowed_pages = ['home', 'about', 'contact'];

// Check if the requested page is allowed
if (in_array($page, $allowed_pages)) {
    // Include the requested page
    include "pages/$page.php";
} else {
    // Include a default error page
    include "pages/error.php";
}
?>