How can PHP be utilized to control access to images on a website based on the referring domain?

When serving images on a website, it may be necessary to restrict access based on the referring domain to prevent hotlinking or unauthorized use. This can be achieved using PHP by checking the HTTP Referer header and allowing access only to specified domains.

<?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 image here
?>