For security I'm moving a collection of files and folders to outside the web root on an apache server, and then I will serve them dynamically. This seems better than 2 alternatives:
So we're back to having them outside the web root but serving them dynamically. The problem I'm having is, since they're all different file types (php scripts, txt, pdf, jpg) I'm not sure whether I should use include()
or readfile()
. And I run into problems with sending the proper headers for every file so that the browser displays them correctly.
Am I missing another magic solution? Is there a framework that has eluded me that handles the serving of dynamic files and headers?
(FYI I'm running Linux, Apache & PHP on a shared host)
I think something like this would work:
<?php
$path = realpath(dirname(__FILE__) . '/../my_files/' . $_GET['file']);
$parts = explode('/', pathinfo($path, PATHINFO_DIRNAME));
if (end($parts) !== 'my_files') {
// LFI attempt
exit();
}
if (!is_file($path)) {
// file does not exist
exit();
}
header('Content-Type: ' . mime_content_type($path));
header('Content-Length: ' . filesize($path));
readfile($path);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With