How can PHP code be modified to ensure secure file inclusion while still allowing for dynamic content loading based on user input?

To ensure secure file inclusion in PHP while still allowing dynamic content loading based on user input, you can use the "realpath" function to validate the path of the file being included. This function resolves any symbolic links and returns the absolute path, which helps prevent directory traversal attacks.

$user_input = $_GET['file']; // Assuming user input is the file to be included

$file_path = realpath('path/to/files/' . $user_input); // Validate the file path

if ($file_path !== false && strpos($file_path, 'path/to/files/') === 0) {
    include $file_path; // Include the file if it is within the allowed directory
} else {
    echo 'Invalid file path'; // Handle error if the file path is invalid
}