PHP readfile()导致文件下载损坏

时间:2012-11-09 16:16:48

标签: php file-io download

我正在使用php脚本在必要的javascript计时器之后从我的网站提供下载这个包含导致下载的PHP脚本。但无论我尝试什么,下载的文件都是腐败的。任何人都可以帮我指出我哪里出错了。

这是我的代码

     <?php
include "db.php";    
 $id = htmlspecialchars($_GET['id']);
 $error = false;
    $conn = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
    if(!($conn)) echo "Failed To Connect To The Database!";
    else{   
        if(mysql_select_db(DB_NAME,$conn)){
            $qry = "SELECT Link FROM downloads WHERE ID=$id";
            try{
                $result = mysql_query($qry);
                if(mysql_num_rows($result)==1){
                    while($rows = mysql_fetch_array($result)){
                        $f=$rows['Link'];
                    }
                    //pathinfo returns an array of information
                    $path = pathinfo($f);
                    //basename say the filename+extension
                    $n = $path['basename'];
                    //NOW comes the action, this statement would say that WHATEVER output given by the script is given in form of an octet-stream, or else to make it easy an application or downloadable
                    header('Content-type: application/octet-stream');
                    header('Content-Length: ' . filesize($f));
                    //This would be the one to rename the file
                    header('Content-Disposition: attachment; filename='.$n.'');
                    //Finally it reads the file and prepare the output
                    readfile($f);
                    exit();
                }else $error = true;
            }catch(Exception $e){
                $error = true;
            }
            if($error) 
            {
                header("Status: 404 Not Found");
                }
        }
  }
?> 

3 个答案:

答案 0 :(得分:18)

这有助于我打开更多输出缓冲区。

//NOW comes the action, this statement would say that WHATEVER output given by the script is given in form of an octet-stream, or else to make it easy an application or downloadable
header('Content-type: application/octet-stream');
header('Content-Length: ' . filesize($f));
//This would be the one to rename the file
header('Content-Disposition: attachment; filename='.$n.'');
//clean all levels of output buffering
while (ob_get_level()) {
    ob_end_clean();
}
readfile($f);
exit();

答案 1 :(得分:11)

首先,正如有些人在评论中指出的那样,在第一行打开PHP标记(<?php)之前删除所有空格,这应该可以解决问题(除非此文件包含或要求其他一些文件)。

当您在屏幕上打印任何内容时,即使是一个空格,您的服务器也会发送标题以及要打印的内容(在这种情况下,您的空白处)。为防止这种情况发生,您可以:

a)在编写标题之前不要打印任何内容;

b)运行ob_start()作为脚本中的第一件事,编写内容,编辑标题,然后在希望将内容发送到用户浏览器时使用ob_flush()和ob_clean()。

在b)中,即使您成功编写标题而没有收到错误,空格也会损坏您的二进制文件。您应该只编写二进制内容,而不是使用二进制内容编写一些空格。

ob _ 前缀代表输出缓冲区。在调用ob_start()时,您告诉您的应用程序您输出的所有内容(echoprintf等)应保留在内存中,直到您明确告诉它“去”({{1} })到客户端。这样,您可以将输出与标题一起保存,当您完成编写后,它们将与内容一起发送。

答案 2 :(得分:0)

           ob_start();//add this to the beginning of your code 

      if (file_exists($filepath) && is_readable($filepath) ) {
header('Content-Description: File Transfer');
 header("Content-Type: application/octet-stream");
 header("Content-Disposition: attachment; filename=$files");
 header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
   header('Pragma: public');
 header("content-length=".filesize($filepath));
 header("Content-Transfer-Encoding: binary");

   /*add while (ob_get_level()) {
       ob_end_clean();
         }  before readfile()*/
  while (ob_get_level()) {
ob_end_clean();
   }
    flush();
   readfile($filepath);