A mod_rewrite solution will be quite elegant, and direct links can be supported.
In .htaccess rewrite all .mp3 links to a PHP script:
RewriteEngine on RewriteRule \.mp3$ download.php
Inside the PHP file, we can extract the requested URI, check the user's IP address and return the appropriate headers based on this check.
<?php // Set variables $requestedFile = trim($_SERVER['REQUEST_URI'], '/'); $ip = $_SERVER['REMOTE_ADDR']; $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0'; // If the file does not exist, throw a 404 error if (!file_exists($requestedFile)) { header($protocol . ' 404 Not Found'); } // Is the user allowed to download? function validateDownload($ip) { /** * Put your IP tracking and validation code here, returning `TRUE` * or `FALSE`. */ return TRUE; } // Validate and perform appropriate action $canDownload = validateDownload($ip); if ($canDownload) { header('Content-Disposition: attachment; filename="' . basename($requestedFile) . '"'); header('Content-type: audio/mpeg'); readfile($requestedFile); } else { header($protocol . ' 403 Forbidden'); }
Now all links remain direct, and you return the appropriate headers to the user agent, requesting a download or denied access.
source share