How can specific folders containing private images be restricted to certain users in PHP?

To restrict access to specific folders containing private images to certain users in PHP, you can utilize sessions and user authentication. When a user logs in, you can store their user ID in a session variable. Then, before serving the images, check if the user is authenticated and has the necessary permissions to access the folder.

<?php
session_start();

// Check if user is logged in
if(!isset($_SESSION['user_id'])) {
    // Redirect to login page or display unauthorized message
    header("Location: login.php");
    exit();
}

// Check if user has permission to access private folder
$allowed_users = array(1, 2, 3); // User IDs with access
if(!in_array($_SESSION['user_id'], $allowed_users)) {
    // Display unauthorized message
    echo "You do not have permission to access this folder.";
    exit();
}

// Serve the private images from the folder
$image_path = 'private_folder/image.jpg';
header('Content-Type: image/jpeg');
readfile($image_path);
?>