What are the potential pitfalls of including external files based on URL parameters in PHP?

Including external files based on URL parameters in PHP can pose security risks, as it opens the door to potential remote code execution attacks. To mitigate this risk, it is important to validate and sanitize any input coming from URL parameters before using it to include external files. This can be done by checking if the file exists in a predefined list of allowed files or directories before including it.

<?php
// Define an array of allowed files
$allowed_files = ['file1.php', 'file2.php'];

// Get the file name from the URL parameter
$file = $_GET['file'] ?? '';

// Check if the file is in the list of allowed files
if (in_array($file, $allowed_files)) {
    include $file;
} else {
    // Handle invalid file request
    echo 'Invalid file request';
}
?>