-1

i have a php web app used by several users. They can upload files in a directory : "files" a sub directory is created with the unique name given to the user "foo" and the file is stored, so: mydomain.com/files/foo/thefilename.doc

It works but to prevent direct access to the file and to prevent others users to access a file they don't belong, i placed a .htaccess file with:

Order Deny,Allow
Deny from all

It works BUT, in my web app if the user "foo" want to access and display his files, he receive a 403 error.

How can i do (like an EDM Electronic Document Management) to store files prevent direct access but give access to the right user?

Thanks a lot

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Alexking2005
  • 325
  • 1
  • 4
  • 16
  • You'll need to create a PHP script that sends the requested file to the user. This gives you control over who can download what and only the PHP script should have access to the actual file system (I would even use file-level permissions for that) – huysentruitw Dec 19 '17 at 08:39
  • Possible duplicate of [How to force file download with PHP](https://stackoverflow.com/questions/7263923/how-to-force-file-download-with-php) – huysentruitw Dec 19 '17 at 08:40
  • I know that my php script can access to these files and generate a download to the client, i made it like that: (...) header("Content-Length: " .(string)(filesize($file)) ); header('Content-Disposition: attachment; filename="'.$filename.'"'); header("Content-Transfer-Encoding: binary\n"); ob_end_clean(); readfile($file); But the file can be an image or a pdf, i would like to open it in the browser – Alexking2005 Dec 19 '17 at 10:04
  • @Alexking2005, commented under my answer, but repeat there (maybe you missed), simply change content-type header based on extention: "image/png", "application/pdf", all modern browsers will process it in a way you want – 2oppin Dec 20 '17 at 09:58

2 Answers2

0

You can do it by getting dynamically with PHP and rendering file-contentens.

Maybe like this:

$filename = $_GET['filename'];
// TODO: fill $allowedFiles[];
if (!in_array($filename, $allowedFiles))
   exit;

header('Content-Type: text');
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0');

echo file_get_contents($filename);

Of course it's just concept

2oppin
  • 1,941
  • 20
  • 33
  • i already use this kinf of script to trigger a download for my users. But in this case the file can be an image or a pdf file, i would like to open it in the browser. – Alexking2005 Dec 19 '17 at 10:08
  • 1
    then simply change content-type header based on extention: "image/png", "application/pdf", all modern browsers will process it in a way you want – 2oppin Dec 19 '17 at 10:39
0

Why don't use a session?

just add <?php session_start() ?> at the begin of each page (before <! DOCTYPE>. And limit the access to some file following the user logged?

More info about the php session