Displaying PDF in browser with PHP not working

Using php's ability to call the browser to display a given PDF, it doesn't work on my web host. But it works on my local xamp server with apache.

PHP:

    $title = $_GET['title'];
    $loc = $_GET['loc'];

    header("Content-type: application/pdf");
    header("Content-Disposition: inline; filename=".$title);
    @readfile($loc);

      

Expected Result: This assumes that the PDF document will render the same as on my local web server.

Actual but unwanted output: % PDF-1.6% 1638 0 obj <> endobj xref 1638 44 0000000016 00000 n ...

You can see it here: http://neilau.me/view.php?title=business-studies-hsc-notes-2006.pdf&loc=pdf/criteria/business-studies/2006/business-studies-hsc-notes-2006. pdf

Is this fixed, changing something on my cpanel? Since my code is not faulty ... It works on my local web server.

+3


source to share


2 answers


You need to make sure that you are not submitting any text before writing the headings.

An example of what not to do :

<!DOCTYPE html>
<html>
...
<?php
header("Content-type: application/pdf");

      

An example of how to fix this:

<?php
header("Content-type: application/pdf");    
?>   
<!DOCTYPE html>
<html>
...

      



Also, your script is very insecure. Here's what you should do, your whole PHP script should be:

<?php
$loc = filter_input(INPUT_GET,"loc");
$title = filter_input(INPUT_GET,'title')?:basename($loc);
if (!is_readable($loc)) {
    http_response_code(404);
    echo "Cannot find that file";
    die();
}
if (strtolower(pathInfo($loc,PATHINFO_EXTENSION)) != "pdf") {
   http_response_code(403);
    echo "You are not allowed access to that file";
    die();
}

header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=".$title);
header("Content-Length: ".filesize($loc));
readfile($loc);

      

If you want to display things like the title of the page or a frame around it, you must use an iframe in another page "wrapper":

<?php 
$loc = filter_input(INPUT_GET,"loc");
$title = filter_input(INPUT_GET,'title')?:basename($loc);
?>
<html><head><title>My title</title></head>
<body>
<iframe src="/view.php?<?php echo ($loc?"loc=$loc":"").($title?"title=$title":"") ?>">
</iframe>
</body>
<html>

      

0


source


Use this code



<?php
$file = 'dummy.pdf';
$filename = 'dummy.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
@readfile($file);
?>

      

+2


source







All Articles