具有fread和readfile的PHP流PDF会生成损坏的pdf [英] PHP stream PDF with fread and readfile produce a damaged pdf

查看:444
本文介绍了具有fread和readfile的PHP流PDF会生成损坏的pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我在使用php流PDF文件时遇到问题,我正在使用以下代码:

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);

        }

这是我的目录布局(因此您可以了解PDF的存储位置):

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

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

如果我从verify.php流式传输pdf文件,则一切按预期方式工作...但是,如果我从login.php流式传输相同的PDF文件,则它们已损坏(损坏).

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).

这是我在login.php中的路径定义

Here my path definition in login.php

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

这是我在verify.php中的路径定义

And here my path definition in verify.php

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

公然的路径定义是在流代码之前.

Obviosly path definition is before che stream code.

pdf文件的平均尺寸最大为50Kb.

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

该文件存在是因为通过了if检查,但是我不知道为什么在一个地方还可以而在另一个地方却被损坏了. (我已将文件签入目录,可以).

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.

感谢: 读取文件无法正常工作

这篇关于具有fread和readfile的PHP流PDF会生成损坏的pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆