How can PHP be used to dynamically generate random image paths for increased security?

When serving images on a website, using predictable image paths can make it easier for attackers to guess and access sensitive images. To increase security, PHP can be used to dynamically generate random image paths. This can be achieved by generating a random string and appending it to the image path when serving the image.

<?php
// Define the base image directory
$baseDir = 'images/';

// Generate a random string for the image path
$randomString = bin2hex(random_bytes(8));

// Define the image file extension
$imageExtension = '.jpg';

// Construct the random image path
$randomImagePath = $baseDir . $randomString . $imageExtension;

// Serve the image using the random path
echo '<img src="' . $randomImagePath . '" alt="Randomly generated image">';
?>