What are the potential security risks of including files in PHP based on user input, as seen in the provided code snippet?

Including files in PHP based on user input can lead to security risks such as remote code execution, directory traversal attacks, and file disclosure vulnerabilities. To mitigate these risks, it is crucial to validate and sanitize user input before using it to include files. One way to do this is to restrict the allowed file paths to a predefined list of safe directories.

// Validate and sanitize user input before including files
$allowed_files = ['file1.php', 'file2.php']; // Define a list of safe files
$user_input = $_GET['file']; // Assuming user input comes from a GET parameter

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