How can PHP developers prevent Cross-Site Scripting vulnerabilities when including files based on user input?

To prevent Cross-Site Scripting vulnerabilities when including files based on user input, PHP developers should sanitize the user input before using it in the include statement. This can be done by validating the input and ensuring that it only contains the expected values, such as predefined file paths.

$allowed_files = array("file1.php", "file2.php", "file3.php");
$user_input = $_GET['file'];

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