I've been going around in circles trying to serve a PDF securely using variations of fopen() and readfile(). Most methods work fine in Firefox and Chrome whether I'm on Windows/OSX/iOS but no method will work with Internet Explorer or Safari. I've tried all sorts of header variations based on what others have suggested but no luck.
Here is my code:
<?php
session_start();
if ($_SESSION['user_is_logged_in'] === true || $_SESSION['admin_user_is_logged_in'] === true) {
$name = $_GET['name'];
$path = "www.mypath.com/$name";
$fp = fopen($path, 'rb');
header("Content-Type: application/pdf");
header("Content-Length: " . filesize($path));
//Experimented with this but all it does is force a download instead of opening in browser.
//header("Content-Disposition: attachment; filename=".$name);
readfile($path);
//alternately tried
//passthru($fp);
}
else {
echo "You do not have permission to view this file. Please <a href='../../index.php'>log in</a>.";
}
exit;
?>
If I use Content-Disposition in the header the result is any PDF downloaded in Safari or IE is 0KB and not readable. Without content-disposition IE and Safari just hang on a blank page.
These are some advices I would like to share:
Try to use localpaths ie. windows (c:\folderesource.pdf) or linux (/var/www/project/resouce.pdf).
Print your $path and check that is a file generated correctly.
Then try this piece of code, that is which I use:
<?php
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename={$this->filename}.pdf");
readfile($path);
unlink($path);