Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php restrict access to files in directory

Tags:

file

php

download

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, i want them to be redirected to the home page.

I have tried the following using htaccess

deny from all

but its not working great. Is there a way i could do this using php, then in the user goes straight to the file in the url, they will get redirected.

So if the user goes to the file link in the url, they will be sent to the home page. So can this only be done using htaccess

like image 313
Daniel Lematy Avatar asked Oct 28 '13 21:10

Daniel Lematy


1 Answers

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);
}
like image 68
Klaus S. Avatar answered Nov 17 '22 06:11

Klaus S.