How can PHP scripts be used to control access to images based on user authentication?

To control access to images based on user authentication using PHP scripts, you can store the images outside of the web root directory and use PHP to check if the user is authenticated before serving the image. This way, unauthorized users cannot directly access the images without proper authentication.

<?php
// Check if user is authenticated
if($authenticated) {
    // Path to the image directory
    $imagePath = '/path/to/images/';

    // Get the image file name from the URL parameter
    $image = $_GET['image'];

    // Serve the image if it exists
    if(file_exists($imagePath . $image)) {
        header('Content-Type: image/jpeg');
        readfile($imagePath . $image);
    } else {
        // Handle error if image does not exist
        echo 'Image not found';
    }
} else {
    // Redirect or show error message for unauthorized users
    echo 'Unauthorized access';
}
?>