What security measures can be implemented in PHP to prevent unauthorized access to dynamically generated images?

To prevent unauthorized access to dynamically generated images in PHP, we can implement security measures such as checking for valid user authentication before serving the image, using unique and hard-to-guess image URLs, and restricting access to the image generation script.

<?php
session_start();

// Check if user is authenticated
if (!isset($_SESSION['authenticated']) || $_SESSION['authenticated'] !== true) {
    header('HTTP/1.1 403 Forbidden');
    exit;
}

// Generate unique image URL
$imageUrl = 'path/to/image_generation_script.php?image_id=' . uniqid();

// Serve the image
echo '<img src="' . $imageUrl . '" alt="Dynamic Image">';
?>