Web-hosted file authorization

48 views Asked by At

Im using a PHP based login authentication mechanism to allow/restrict access to some parts of my website (folder module1, module2, etc), but i have a problem with restricting access to files. I used the documents folder (check below) to host some downloadable files. The links to those files appear in index.php (hosted in the root directory). However if for some reason a non-authorized user get the URL of the files hosed in documents he will be able to download it.

/
/documents/
/module1/
/module2/

PS: as this is an intranet website I restricted the access to documents by IPs, but there is still a small chances that someone use a PC with allowed IP address and he have the URL of the document.

1

There are 1 answers

0
Daniel On

Use some sort of a proxy PHP script that will serve the file for the user without giving the real source location.

The user would then see http://yourdomain.com/download.php?file=mydoc.docx

The real path is still /documents/userid/2342/mydoc.docx or what ever your structure looks like.

Then let your download.php file serve the file by:

<?php
// Validate the user here

// Set document root
$root = 'documents/userid/'.$userID.'/';

// Requested file
$file = $_GET['file'];

// Validate
if (file_exists($root . $file))
{
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private", false);
    header("Content-Type: application/force-download");
    header("Content-Disposition: attachment; filename=\"".basename($file)."\";");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".filesize($root . $file));

    ob_clean();
    flush();
    readfile($root . $file);
}
else { echo "File not found"; }
?>

See more here