psfan 发表于 2012-10-30 16:16

php做的下载代码自动添加bom头?

<?php

function downloadfile(){
      $file_name = "test.rar";
      $file_dir ="./";
      if (!file_exists($file_dir."/".$file_name)){
         return false;
         exit;
      }else{
         $file = fopen($file_dir."/".$file_name,"r");
         header('Content-Encoding: none');
         header("Content-type: application/octet-stream");
         header("Accept-Ranges: bytes");
         header("Accept-Length: ".filesize($file_dir."/".$file_name));
         header( 'Content-Transfer-Encoding: binary' );
         header("Content-Disposition: attachment; filename=" .$file_name);
         header('Pragma: no-cache');
         header('Expires: 0');
         echo fread($file,filesize($file_dir."/".$file_name));
         fclose($file);
         exit;
      }
      }
      downloadfile();
?>就这样一段代码,能实现客户端下载制定文件,但现在遇到问题是客户端下载完成后test.rar压缩包打不开,用UE打开文件头一看,下载的文件自动在开头添加了EF BB BF 20这4个字节,查baidu知道前三个是UTF8的BOM标识,最后一个是空格,现在问题是不知道这4个字节是在哪一步插进去的,请教高人指点如何传送正确的文件给客户端呢?

rainysia 发表于 2012-10-31 09:38

我刚试了下.因为我在linux下.
所以压缩的时候是压成了test.tar.gz
然后直接下载后能打开

再换成.rar 后,下载后就打不开了.出现了你这个问题

我估计是 header('Content-Encoding: none');
         header("Content-type: application/octet-stream");
         header("Accept-Ranges: bytes");
         header("Accept-Length: ".filesize($file_dir."/".$file_name));
         header( 'Content-Transfer-Encoding: binary' );
这几个header产生的.

satrun7 发表于 2012-10-31 11:54

用你的代码,我测试一下windows 7 下 php 5.4.0 + apache 2.2.22 , 下载rar,zip文件都没问题。
估计和LZ的php文件编码有关系。

psfan 发表于 2012-11-01 07:52

回复 3# satrun7


    谢谢提醒,我按这个线索再查查看。

cogobuy123 发表于 2012-11-01 14:50

:-L新手还要好的学习~~

yifangyou 发表于 2012-11-03 23:00

自动加bom是你的php文件格式的问题,你的php文件里有bom头的话,php执行时会把它一块输出,你用16进制看一下你的php的前三个字节

psfan 发表于 2012-12-05 13:41

回复 6# yifangyou


    的确是这样,要用HexEditor才能看到隐藏字符。

maochanglu 发表于 2012-12-06 09:42

用 notepad + +也可以看得到bom头。
页: [1]
查看完整版本: php做的下载代码自动添加bom头?