How can PHP be optimized to efficiently handle file inclusion based on user input?

To efficiently handle file inclusion based on user input in PHP, it is important to sanitize and validate the user input to prevent directory traversal attacks. One way to achieve this is by using a whitelist approach, where only allowed files are included based on the user input. Additionally, caching file inclusions can help improve performance by reducing the number of file system operations.

$user_input = $_GET['file'];

$allowed_files = ['file1.php', 'file2.php', 'file3.php'];

if (in_array($user_input, $allowed_files)) {
    include($user_input);
} else {
    echo "Invalid file";
}