What are the potential security risks of reading external HTML or PHP files using PHP code?

Reading external HTML or PHP files using PHP code can pose security risks such as code injection, cross-site scripting (XSS) attacks, and potential exposure of sensitive information. To mitigate these risks, it is important to validate and sanitize the input from the external files before processing or displaying it.

$file = 'external_file.html';

// Validate the file path
if (strpos($file, 'path/to/allowed/directory/') !== 0) {
    die('Invalid file path');
}

// Sanitize the input
$content = file_get_contents($file);
$content = htmlspecialchars($content);

// Display the sanitized content
echo $content;