What are the potential security risks of including files based on user input in PHP?

Including files based on user input in PHP can lead to security risks such as directory traversal attacks, allowing malicious users to access sensitive files on the server. To mitigate this risk, it is important to validate and sanitize user input before using it to include files.

$user_input = $_GET['file'];

// Validate and sanitize user input
$allowed_files = ['file1.php', 'file2.php', 'file3.php'];
if (in_array($user_input, $allowed_files)) {
    include($user_input);
} else {
    echo "Invalid file input";
}