How can PHP developers ensure that images are securely served to users while maintaining performance and efficiency?

To ensure that images are securely served to users while maintaining performance and efficiency, PHP developers can implement image hotlink protection. This involves checking the HTTP Referer header to verify that the request for the image is coming from an allowed domain. If the request is not from an allowed domain, the server can respond with a 403 Forbidden error or serve a placeholder image instead.

<?php
$allowed_domains = array('example.com', 'subdomain.example.com');

$referer = $_SERVER['HTTP_REFERER'];

if($referer){
    $referer_host = parse_url($referer, PHP_URL_HOST);
    
    if(!in_array($referer_host, $allowed_domains)){
        header("HTTP/1.0 403 Forbidden");
        exit;
    }
} else {
    header("HTTP/1.0 403 Forbidden");
    exit;
}

// Serve the image here
?>