Are there any best practices for reading and displaying content from a file in PHP?

When reading and displaying content from a file in PHP, it is important to handle errors, properly open and close the file, and sanitize the content before displaying it to prevent security vulnerabilities. One best practice is to use file_get_contents() to read the file contents and htmlspecialchars() to sanitize the content before displaying it.

$file = 'example.txt';

if(file_exists($file)){
    $content = file_get_contents($file);
    $sanitized_content = htmlspecialchars($content);
    
    echo $sanitized_content;
} else {
    echo 'File not found.';
}