Trondro Mulligan
Trondro Mulligan

Reputation: 505

How to make files ONLY downloadable, not readable by client

I'm working on a php script where users can upload any type of file they want, even php files.

All files are uploaded/moved in a specific folder ("uploads").

I don't want these files to be readable otherwise it can cause a major security bug as users can write any php code and take control of my server.

I want these files only to be downloadable by the user client (browser). Like Dropbox for example.

Upvotes: 0

Views: 133

Answers (1)

Victor Radu
Victor Radu

Reputation: 2292

you can deny acces to uploads/move, then force a redirect from all URLS under uploaded/moved to a PHP script

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^/uploads/move/(.*)$ /serve_file.php?filePath=$1 [L]

then send a force download header like so for example:

header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Type: application/force-download");
header("Content-Length: " . filesize($filePath));
header("Connection: close");
readfile($filepath);
exit;

!!Make sure the $filePath is in uploads/move and not anywhere else or they could grab other files)!!

Thanks @Mark Baker for the optimisation, using readfile is a better way!

Upvotes: 1

Related Questions