下载器代码可能有问题,导致PDF文件损坏

WBOY
Release: 2016-06-23 14:01:05
Original
1586 people have browsed it

服务器中的PDF文件是健康的:通过FTP直接下载来验证过。
下载器的部分代码如下:

$file_size = filesize($filedir);
header("Content-type: application/octet-stream;charset=ISO-8859-1");
header("Cache-control: private");
header("Accept-Ranges: bytes");
header("Accept-Length: ".$this->FjSize);
header("Content-Disposition: attachment; filename=" . $this->delFileName);
$fp = fopen($filedir,"r");
$buffer_size = 1024;
$cur_pos = 0;
while(!feof($fp) && $filedir-$cur_pos > $buffer_size)
{
$buffer = fread($fp,$buffer_size);
echo $buffer;
$cur_pos += $buffer_size;
}

if($file_size > 0)
$buffer = fread($fp,$file_size-$cur_pos);
else
$buffer = fread($fp,$this->FjSize);
echo $buffer;
fclose($fp);
flush();


回复讨论(解决方案)

$fp = fopen($filedir,"r b"); //二进制方式打开,虽然 linux 不需要,但仍建议这么做
文本方式打开的文件,0x1a 就视为文件尾了

while(!feof($fp) && $filedir-$cur_pos > $buffer_size)
宜写作
while(!feof($fp))
feof($fp) 就是文件尾了
再 $filedir-$cur_pos > $buffer_size 已无必要
双重判断可能导致失误,比如 $filedir 不是 $buffer_size 整数倍时

另外,除文件内容外,不能输出任何其他内容,包括 BOM 头

按照版主说的改了。照样出错。
PS:程序过去一年都运行良好,最近几天才出问题。

上传了一个文件,内容如下

1234567890
abcdefghijklmnopqrstuvwxyz

然后下载到本地,结果如下

?      2426153钒4噱JLJNIMK先淌紊退/(,*.)-+??   ?? ??&   

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!