How can the PHP function readfile() be properly utilized to display the contents of a text file on an HTML page without errors?

The PHP function readfile() can be utilized to display the contents of a text file on an HTML page without errors by using proper error handling and ensuring that the file path is correctly specified. To achieve this, you should check if the file exists before attempting to read it and handle any errors that may occur during the file reading process.

<?php
$file = "example.txt";

if (file_exists($file)) {
    readfile($file);
} else {
    echo "File not found.";
}
?>