How can PHP developers prevent unauthorized code execution when including files dynamically?

To prevent unauthorized code execution when including files dynamically in PHP, developers should validate user input and ensure that only allowed files are included. One way to do this is by using a whitelist approach, where only specific files or directories are allowed to be included dynamically.

$allowed_files = array('file1.php', 'file2.php');

if (in_array($_GET['file'], $allowed_files)) {
    include $_GET['file'];
} else {
    // Handle unauthorized file inclusion
    echo "Unauthorized file inclusion attempt.";
}