What are some best practices for dynamically including PHP files based on user input?

When dynamically including PHP files based on user input, it is important to validate and sanitize the user input to prevent security vulnerabilities such as directory traversal attacks. One common approach is to use a switch statement to determine which file to include based on the user input, ensuring that only allowed files are included.

// Validate and sanitize user input
$user_input = $_GET['file'];
$allowed_files = ['file1.php', 'file2.php', 'file3.php'];

if (in_array($user_input, $allowed_files)) {
    // Dynamically include the specified file
    include($user_input);
} else {
    // Handle invalid input
    echo "Invalid file specified";
}