What is the best way to display an image from a folder without directly linking to it in PHP?

When displaying an image from a folder in PHP, it is best practice to prevent direct linking to the image file for security reasons. One way to achieve this is by using a PHP script to read the image file from the folder and then output it to the browser. This way, the image is not directly accessible by its URL.

<?php
$imagePath = 'images/image.jpg';

// Get the image MIME type
$imageType = pathinfo($imagePath, PATHINFO_EXTENSION);

// Set the appropriate Content-Type header
header("Content-Type: image/{$imageType}");

// Output the image file
readfile($imagePath);
?>