What are the advantages and disadvantages of using PHP scripts to output images for protection?

When outputting images using PHP scripts for protection, the main advantage is that it allows for greater control over access to the images, such as requiring authentication or restricting access based on certain conditions. However, this method can also increase server load and slow down the loading of images compared to directly linking to them. It is important to weigh the benefits of added security against the potential drawbacks in performance.

<?php
// Check if user is authenticated before serving the image
if($authenticated) {
    $imagePath = 'path/to/image.jpg';
    $imageInfo = getimagesize($imagePath);
    
    header('Content-Type: ' . $imageInfo['mime']);
    readfile($imagePath);
} else {
    // Output a placeholder image or error message
    $placeholderImage = 'path/to/placeholder.jpg';
    $imageInfo = getimagesize($placeholderImage);
    
    header('Content-Type: ' . $imageInfo['mime']);
    readfile($placeholderImage);
}
?>