You might find some better info in the link provided by @soac, but here is an excerpt from some of my code for PDF files only:
<?php
$file = ( !empty($_POST['file']) ? basename(trim($_POST['file'])) : '' );
$full_path = '/dir1/dir2/dir3/'.$file; // absolute physical path to file below web root.
if ( file_exists($full_path) )
{
$mimetype = 'application/pdf';
header('Cache-Control: no-cache');
header('Cache-Control: no-store');
header('Pragma: no-cache');
header('Content-Type: ' . $mimetype);
header('Content-Length: ' . filesize($full_path));
$fh = fopen($full_path,"rb");
while (!feof($fh)) { print(fread($fh, filesize($full_path))); }
fclose($fh);
}
else
{
header("HTTP/1.1 404 Not Found");
exit;
}
?>
Note that this opens the PDF in the browser rather than downloading it perse, although you can save the file locally from within the reader. Using readfile()
would probably be more efficient (and cleaner code) than the old way of opening the file via a handle the way I do in this example.
readfile($full_path);