What are some best practices for ensuring that images generated by a PHP script are only visible on specific websites?

To ensure that images generated by a PHP script are only visible on specific websites, you can check the referrer header in the HTTP request to verify that the request is coming from an allowed domain. This can help prevent hotlinking and unauthorized use of your images.

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

$referrer = $_SERVER['HTTP_REFERER'];

if($referrer) {
    $referrer_host = parse_url($referrer, PHP_URL_HOST);
    
    if(!in_array($referrer_host, $allowed_domains)) {
        // Redirect or display an error message
        header('Location: unauthorized.php');
        exit;
    }
} else {
    // Redirect or display an error message
    header('Location: unauthorized.php');
    exit;
}

// Your image generation code here