How can the problem of displaying garbled text instead of images be resolved in PHP?

When displaying images in PHP, garbled text may appear due to incorrect headers being sent before the image data. To resolve this issue, make sure to send the correct headers before outputting the image data using the header() function. This will ensure that the browser interprets the data as an image rather than text.

<?php
// Set the content type header to indicate that the data is an image
header('Content-Type: image/jpeg');

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