Are there any best practices for securely protecting files from external linking in PHP?

To securely protect files from external linking in PHP, you can check the HTTP referer header to ensure that the request is coming from your own domain. This helps prevent hotlinking, where other websites directly link to your files, consuming your bandwidth.

<?php
$referer = $_SERVER['HTTP_REFERER'];

if ($referer && !parse_url($referer, PHP_URL_HOST) == 'yourdomain.com') {
    header('HTTP/1.0 403 Forbidden');
    exit;
}

// Serve the file here