How can PHP be used to control access to images based on user login status?

To control access to images based on user login status in PHP, you can create a script that checks if the user is logged in before serving the image. This can be done by setting up a session variable upon successful login and then checking this variable before displaying the image.

<?php
session_start();

if(isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
    // User is logged in, serve the image
    $imagePath = 'path/to/image.jpg';
    header("Content-Type: image/jpeg");
    readfile($imagePath);
} else {
    // User is not logged in, display an error message or redirect to login page
    echo "You do not have permission to access this image.";
    // header("Location: login.php"); // Uncomment this line to redirect to login page
}
?>