I have a function called “viewDoc” which is supposed to go to a folder outside the web root and fetch a file for me. It seams to work ok with images (Jpgs etc) but with PDF’s it just outputs a blank gray page as demonstrated here – http://www.tutorplanner.com/userimage/viewdoc/12787622467.pdf
Can anyone see what I’m doing wrong as I’ve been scratching my head over this for a day!
public function viewDoc($doc) {
$path_parts = pathinfo($_SERVER['REQUEST_URI']);
$file = $doc;
$fileDir = '/var/uploads/';
if (file_exists($fileDir . $file))
{
$contents = file_get_contents($fileDir . $file);
//print_r($contents);
header('Content-Type: ' . mime_content_type($fileDir . $file));
header('Content-Length: ' . filesize($fileDir . $file));
readfile($contents);
}
}
readfile is used with the parameter of a file name – NOT text.
Two examples that would work (file_get_contents):
or (readfile):
I also added the
$filePathvariable for you, as there’s no reason to concat the string multiple times.Edit
As extra security, to Yazmat’s comment, you can use
$file = str_replace(array('..', '/'), '', $doc);as this would remove all references to other directories (however, with the slash it would also remove access to sub directories, so you might want to skip that, dependend on your code and file structure).