What are potential security risks when using dynamic loading in PHP?

Potential security risks when using dynamic loading in PHP include the possibility of loading malicious code or files from external sources, leading to code execution vulnerabilities. To mitigate these risks, it is essential to validate and sanitize input data before using it to dynamically load files or classes.

// Example of validating and sanitizing input data before dynamic loading
$allowed_files = ['file1.php', 'file2.php', 'file3.php']; // List of allowed files

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

if (in_array($file, $allowed_files)) {
    require_once($file); // Dynamically load the file if it is in the allowed list
} else {
    // Handle invalid file request
    echo "Invalid file request";
}