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

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

$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 specified";
}