使用 fread 和 readfile 的 PHP 流 PDF 生成损坏的 pdf
大家好,我在使用 php 流式传输 PDF 文件时遇到问题,我正在使用以下代码:
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 的存储位置):
Parent/
verify.php
auth/
pdf/
login.php
如果我从 verify.php 流式传输 pdf,则一切都按预期工作...但是如果我从 login.php 流式传输相同的 PDF 文件,它们就会损坏(损坏)。
这里是我在 login.php 中的路径定义
$path = "pdf/" . $filename . "_print.pdf";
这里是我在 verify.php 中的路径定义
$path = "auth/pdf/" . $filename . "_print.pdf";
显然路径定义是在 che 流代码之前。
pdf 文件的平均尺寸最大为 50Kb。
该文件存在是因为通过了 if 检查,但我不知道为什么一个地方没问题而另一个地方损坏了。 (我已经将文件检查到目录中没有问题)。
抱歉我的英语不好,提前谢谢你。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我解决了这样编辑代码的问题:
路径有两种工作方式:相对或绝对。
由于:
读取文件无法正常工作
i fixed the issue editing the code like this:
The path work in both ways: relative or absolute.
Thanks to:
readfile not working properly
您当前的工作目录不会根据您的包含脚本路径而改变。因此,如果
/var/www/parent/auth/login.php
包含在/var/www/parent/index.php
中,您的工作目录将保留/ var/www/parent
。处理这个问题的流行方法是在主文件中定义一个
define('BASEPATH', dirname(__FILE__));
(BASEPATH='/var/www/parent') 常量,并使用它在其他地方: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: