What is the best way to restrict access to a PHP file from external domains?

To restrict access to a PHP file from external domains, you can check the HTTP referer header to ensure that the request is coming from an allowed domain. This helps prevent hotlinking and unauthorized access to your PHP files.

<?php
$allowed_domains = array('example.com', 'subdomain.example.com');
$referer = isset($_SERVER['HTTP_REFERER']) ? parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST) : '';

if (!in_array($referer, $allowed_domains)) {
    header('HTTP/1.1 403 Forbidden');
    exit('Access denied');
}

// Your PHP code here
?>