Just store the file out of the root directory that holds all of your front-facing files. So assuming your directory structure is as such:
root
-- public_html
-- -- access_book.php
-- -- index.php
-- -- ...
-- books
-- -- mobi_dick.pdf
-- -- ...
Then, just grab your file with a relative path (here is an example pulled from readfile
):
<?php
// Replace this with the path to the actual file
$file = '../books/mobi_dick.pdf';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
?>
You may have to configure open_basedir
for PHP to open a file outside of the web root.