PHP stream PDF with fread and readfile produce a damaged pdf

帅比萌擦擦* 提交于 2019-12-25 01:36:50

问题


Hello guys i have a problem streaming PDF files with php, i'm using this code:

if(file_exists($path))
        {
            //octet-stream 
            header("Content-Length: " . filesize ( $path ) ); 
            header("Content-type: application/octet-stream"); 
            header("Content-disposition: attachment; filename=".basename($path)); 
            readfile($path);

        }

This is my directory layout (so you can understand where the PDF are stored):

Parent/
  verify.php
  auth/
    pdf/
    login.php

If i stream the a pdf from verify.php all works as intended... but if i stream the SAME PDF file from login.php they are corrupted (damaged).

Here my path definition in login.php

$path = "pdf/" . $filename . "_print.pdf"; 

And here my path definition in verify.php

$path = "auth/pdf/" . $filename . "_print.pdf"; 

Obviosly path definition is before che stream code.

The average dimension of pdf files are up to 50Kb.

The file exists beacuse pass the if check but i've no clue about why in one place is ok and in the other is damaged. (i've checked the file into the directory are okay).

Sorry for my poor english and thank you in advance.


回答1:


i fixed the issue editing the code like this:

header("Content-Length: " . filesize ( $path ) ); 
                header("Content-type: application/octet-stream"); 
                header("Content-disposition: attachment; filename=".basename($path));
                header('Expires: 0');
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                ob_clean();
                flush();

                readfile($path);

The path work in both ways: relative or absolute.

Thanks to: readfile not working properly




回答2:


Your current working derictory doesn't change depending on your included script path. So if /var/www/parent/auth/login.php is included by /var/www/parent/index.php your working directory will remain /var/www/parent.

The popular way to deal with this is to define a define('BASEPATH', dirname(__FILE__)); (BASEPATH='/var/www/parent') constant in your main file, and use it everywhere else:

//in verify.php
$path = BASEPATH . "/auth/pdf/" . $filename . "_print.pdf";

//in login.php
$path = BASEPATH . "/auth/pdf/" . $filename . "_print.pdf";


来源:https://stackoverflow.com/questions/6055259/php-stream-pdf-with-fread-and-readfile-produce-a-damaged-pdf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!