开发者

PHP stream PDF with fread and readfile produce a damaged pdf

开发者 https://www.devze.com 2023-03-07 10:37 出处:网络
Hello guys i have aproblem streaming PDF files with php, i\'m using this code: if(file_exists($path)) {

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 pa开发者_开发问答th 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.


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


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";
0

精彩评论

暂无评论...
验证码 换一张
取 消