2012-02-19 44 views
1

我想實現的是強制通過PHP下載文件。 我面臨兩個問題,我已經打破了頭腦,想着這裏可能會出現什麼問題。PHP強制下載文件 - 要麼下載中斷或系統說無效/損壞的文件

  1. 每當我試着下載使用IE文件,下載被中斷約中途即說我的文件是1024KB的大小,周圍500KB是當下載停止,因爲我得到IE的錯誤消息說,「下載爲中斷'
  2. 我經常遇到的其他問題(但並不總是)是由於某種原因,下載的文件(實際上是一個zip文件)有時會被損壞!服務器上的文件是好的 - 如果我直接從那裏下載它,根本沒有問題。然而,如果我使用我的PHP腳本下載,然後嘗試解壓文件 - Windows說'無效或損壞的文件...'

我真的需要一些幫助。

以下是代碼下載該文件的塊: -

$fileName = "./SomeDir/Somefile.zip"; 
$fsize = filesize($fileName); 
set_time_limit(0); 

// required for IE, otherwise Content-Disposition may be ignored 
if(ini_get('zlib.output_compression')) 
ini_set('zlib.output_compression', 'Off'); 


// set headers 
header("Pragma: public"); 
header("Expires: 0"); 
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header("Cache-Control: public"); 
header("Content-Description: File Transfer"); 
header('Content-type: application/zip'); 
header("Content-Disposition: attachment; filename=\"".basename($fileName)."\";"); 
header("Content-Transfer-Encoding: binary"); 
header('Accept-Ranges: bytes'); 
header("Content-Length: " . $fsize); 

// download 
$file = @fopen($fileName,"rb"); 
if ($file) { 
    while(!feof($file)) { 
print(fread($file, 1024*8)); 
flush(); 
if (connection_status()!=0) { 
    @fclose($file); 
    die(); 
} 
} 
@fclose($file); 
} 

回答

1

試試這個

<?php 

$file = "./SomeDir/Somefile.zip"; 
set_time_limit(0); 
$name = "Somefile.zip"; 

// Print headers and print to output. 
header('Cache-Control:'); 
header('Pragma:'); 
header("Content-type: application/zip"); 
header("Content-Length: ". filesize($file)); 
header("Content-Disposition: attachment; filename=\"{$name}\""); 
readfile($file); 

?> 
+0

感謝您的快速響應。嘗試了這一點,它似乎顯示相同的行爲:(有時下載的文件已損壞或無效,IE突然停止下載並說'下載被中斷' – Rohan 2012-02-19 13:08:50

+0

可能嘗試使用不同的內容類型:而不是應用程序/ zip,嘗試使用應用程序/八位字節流。看看是否有幫助。 – 2012-02-23 04:07:28

0

我覺得比你的量內容長度報告多個字節真的轉移。 檢入服務器的日誌。服務器可以gzip內容,當它關閉連接時,客戶端仍在等待剩餘的聲明字節。

+0

這篇文章可能是一個評論 – marsei 2013-09-30 11:06:36