How can PHP be used to restrict access to specific images for only authenticated users?

To restrict access to specific images for only authenticated users in PHP, you can check if the user is authenticated before serving the image file. This can be done by verifying the user's authentication status using session variables or any other authentication mechanism.

<?php
session_start();

// Check if user is authenticated
if (!isset($_SESSION['authenticated']) || $_SESSION['authenticated'] !== true) {
    // Redirect or display error message
    header("Location: login.php");
    exit();
}

// Serve the image file
$imagePath = 'path/to/image.jpg';
header('Content-Type: image/jpeg');
readfile($imagePath);
?>