4

I need to secure a folder. Website was done in PHP. There is an admin area with files like PDF, DOC… so; I cannot protect these files with session variable. Is there a way in PHP to protect a folder?

Thank you

Lenny
  • 41
  • 1
  • 1
  • 2
  • 5
    While this doesn't answer your question, as such, you do know that you can move files outside of the web-root, and have them still-accessible by the server and scripts thereon? If you have an authorisation mechanism then they should be just as safe, if not safer, there than in a php-protected directory. – David Thomas Jun 25 '10 at 17:49
  • I'd agree with @ricebowl...if these files aren't meant to be served directly via the website, it makes sense to place them outside of the web-root and access them via script only. – Robert Hui Jun 25 '10 at 18:18

2 Answers2

4

You can't protect it using only PHP, but with the help of a .htaccess file, this is possible.

Create a .htaccess file in the directory you want to protect, and put this in it:

Deny from all

Then, to create a PHP script to access the files, you can do something like this:

// Add user authentication code
$name = 'protected_dir/file.pdf';
$fp = fopen($name, 'rb');
header("Content-Type: application/pdf");
header("Content-Length: " . filesize($name));
fpassthru($fp);
exit;
David Barnes
  • 2,138
  • 5
  • 19
  • 25
1

You can put your files behind the viewable area(before public_html) and with a session protected download page, download the files.

<?php
if(session_is_loggedin()){
    readfile($_GET['file']);

}
?>

Obviously, there need to be some extra changes but that is the part you requested.

nebkat
  • 8,445
  • 9
  • 41
  • 60