What are the best practices for handling headers in PHP scripts when displaying images?

When displaying images in PHP scripts, it is important to set the appropriate headers to ensure the image is displayed correctly in the browser. This includes setting the content type header to specify the image type (e.g. image/jpeg, image/png) and sending the image data to the output buffer. Failing to set the correct headers can result in the image not displaying properly or causing errors.

<?php
// Set the content type header based on the image type
header('Content-Type: image/jpeg');

// Output the image data
$image = file_get_contents('image.jpg');
echo $image;
?>