What best practices should be followed when using readfile to load images in PHP to avoid server errors?

When using readfile to load images in PHP, it is important to handle errors properly to avoid server issues. One common best practice is to check if the file exists before attempting to read it. Additionally, setting the appropriate headers and using proper error handling can help prevent any potential problems.

$filename = 'image.jpg';

if (file_exists($filename)) {
    header('Content-Type: image/jpeg');
    readfile($filename);
} else {
    echo 'Image not found';
}