phphtmlx-sendfile

Problems embedding PDF file sent with XSendFile in a webpage


I'd like to embed a PDF file in a webpage. I need to dynamically produce the PDF so I can authenticate the user first, so I'm using XSendFile on Apache. The PHP file I have works fine when I visit a browser with the PDF file being immediately offered for download. Here is the code I'm using (courtesy of http://www.brighterlamp.com/2010/10/send-files-faster-better-with-php-mod_xsendfile/)

// Get a list of loaded Apache modules
$modules = apache_get_modules();
if (in_array('mod_xsendfile', $modules)) {
    // Use XSendFile if possible
    header ('X-Sendfile: ' . $pathToFile);
    header ('Content-Type: ' . $documentMIME);
    header ('Content-Disposition: attachment; filename="' . $actualFilename . '"');
    exit;
} else {
    // Otherwise, use the traditional PHP way..
    header ('Content-Type: ' . $documentMIME);
    header ('Content-Disposition: attachment; filename="' . $actualFilename . '"');
    @ob_end_clean();
    @ob_end_flush();
    readfile($pathToFile);
    exit;
}

So far so good. Now I want to embed this PDF in a webpage using an object tag e.g.:

<object data="dynamicpdf.php" type="application/pdf">
   <p>PDF embed failed</a></p>
</object>

But this fails. If I switch the data attribute to a static PDF file then it works fine.

Any ideas what is going wrong?


Solution

  • Is iframing the PDF an option for you?

    Like <iframe src="dynamicpdf.php">

    The Content-Disposition header forces the download. Remove it.

    General Advise: I would not use functions like apache_get_modules that asume a specific webserver environment.

    What if you switch away from mod_php or apache in future? Your code will break.

    Instead I would do the delivery in a streamed php response that is more memory efficient than output buffering the whole PDF into RAM and then send it.

    By streaming the PDF out with PHP you would also have only one implementation and it would be same speed as x-sendfile is:

    Streaming a large file using PHP