From what I get from your use case from your description, you can solve your problem using only one of the already available Wordpress plugins, for example, you can use the “downnload manager” to handle upload and download content: https: // wordpress .org / support / plugin / download-manager or use something like https://wordpress.org/plugins/easy-digital-downloads/
Here you can find more plugins https://wordpress.org/plugins/
If you really want to write something custom, you can add a RewriteRule to send all the requests for the uploads folder through the "protect.php" script, adding something like this to the .htaccess file
RewriteCond %{REQUEST_FILENAME} -s RewriteRule ^wp-content/uploads/(.*)$ protect.php?filename=$1 [L,QSA]
In the protect.php script file, you can implement custom logic to allow / deny access to a specific "file name"
To use the WP functions inside the user protect.php file, you must include wp-load.php, more or less as follows:
require_once(rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/wp-load.php');
source share