2011-12-10 39 views
0

我寫了一個PHP腳本來強制下載文件給用戶。一切都很好,但有一個例外,該文件沒有完全下載假設有一個10 MB的mp3文件下載,但它停止5 MB後顯示下載完成。在php中強制下載的問題

我的網站主機是godaddy.com
和代碼低於

<?php 
if(ini_get('zlib.output_compression')) { 
    ini_set('zlib.output_compression', 'Off'); 
} 

if (isset ($_REQUEST['file_name'])) { 
    $filename = basename($_REQUEST['file_name']); 
    $filesize = filesize("mp3gallery/".$_REQUEST['file_name']); 

    header("Pragma: public"); 
    header("Expires: 0"); 
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
    header("Cache-Control: private",false); 
    header("Content-length: $filesize"); 
    header("Content-Transfer-Encoding: binary"); 
    header('Content-type: audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3'); 
    header('Content-Disposition: attachment; filename="'.$filename.'"'); 

    $read_file = "mp3gallery/".$_REQUEST['file_name']; 




    function readfile_chunked($filename,$retbytes=true) { 
     $chunksize = 1*(1024*1024); // how many bytes per chunk 
     $buffer = ''; 
     $cnt =0; 
     // $handle = fopen($filename, 'rb'); 
     $handle = fopen($filename, 'rb'); 
     if ($handle === false) { 
      return false; 
     } 
     while (!feof($handle)) { 
      $buffer = fread($handle, $chunksize); 
      echo $buffer; 
      ob_flush(); 
      flush(); 
      if ($retbytes) { 
       $cnt += strlen($buffer); 
      } 
     } 
      $status = fclose($handle); 
     if ($retbytes && $status) { 
      return $cnt; // return num. bytes delivered like readfile() does. 
     } 
     return $status; 

    } 
    readfile_chunked($read_file,true); 
} 
?> 

請幫助.........

回答

1

這個問題可能是你的腳本超時。

那麼你能做什麼?

  • 更改時間限制(也許不可能的,因爲你的主機託管服務提供商不會讓你)
  • 要加快處理速度

關於後者:有沒有你爲什麼不特定的理由只需使用fpassthru?我希望它有更好的表現。

0

試試這個:

function download($data , $fName) { 
     header(sprintf('Expires: %s' , strftime('%a, %d %b %Y %H:%M:%S GMT' , strtotime('+1 year' , time())))); 
     header('Cache-Control: no-cache, must-revalidate'); 
     header('Pragma: public, no-cache'); 
     header(sprintf('Content-Disposition: attachment; filename="%s"' , $fName)); 
     header(sprintf('Content-Description: %s' , uniqid())); 
     if (is_file($data)) { 
       $filePath = sprintf('%s/%s' , $_SERVER[ 'DOCUMENT_ROOT' ] , $data); 
       if (file_exists($data)) { 
         if (version_compare(PHP_VERSION , '5.3.0' , '<')) 
           header(sprintf('Content-Type: %s' , mime_content_type($filePath))); 
         else 
           header(sprintf('Content-Type: %s' , finfo_file(finfo_open(FILEINFO_MIME_TYPE) , $filePath))); 
         header(sprintf('Content-Length: %d' , filesize($filePath))); 
         readfile($data); 
       } 
     } else { 
       echo $data; 
     } 
    } 
+1

您可能要添加的,我們應該OP試試這個。你的代碼做得更好嗎? – middus