I am trying to restrict direct access to files in a directory. So for example i have website.com/files/example.flv.
So if users go straight to the file in the URL,
If you want to restrict access to files, you should consider storing them outside the public DocumentRoot and using PHP to deliver the file, applying your own access logic. This means outside the www or public_html folders, depending on the hosting environment you are working with.
<?php
// Suppose your "public_html" folder is .
$file = './../data/test.gif';
$userCanDownloadThisFile = false; // apply your logic here
if (file_exists($file) && $userCanDownloadThisFile) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=filename.gif');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
}
Yes. You'd have to place the files in a directory that's not accessible through the web. Then, you'd have to create a .htaccess file in your public_html/files/ folder, which points to your php script.
Something like this (note: code not tested):
Structure:
.htaccess:
RewriteEngine on
RewriteRule ^/files/(.+)$ filehandler.php?stuff=$1 [QSA]
filehandler.php:
header('Location: /');
Of course you'd want the files to be accessible when you want them to access them. This can be done in filehandler.php, by checking if the user is allowed to view the file, and then returning something like:
header('Content-type: application/octet-stream');
header('Content-Disposition: inline; filename="'.basename(urlencode($file['name'])).'"');
readfile($dir.basename($file['filename']));
exit;