2016-09-28 48 views
0

我寫了下面的代碼,允許下載沒有顯示源文件。PHP File Down with header()

在此示例中,文件'test.pdf'已下載,但已損壞。

任何人都可以看到任何理由,這將是這種情況?

$path = 'http://www.domain.org/images/uploads/test.pdf'; 

// Directory Path 
$directory_path_filename = str_replace('http://www.domain.org/', '', $path); 

$filepath = '/var/sites/l/domain.org/public_html/'.$directory_path_filename; 

if (file_exists($filepath)) { 

    $finfo = finfo_open(FILEINFO_MIME); 
    header('Content-Type: application/pdf'); 
    header('Content-Disposition: attachment; filename= ' . basename($filepath)); 
    header('Content-Length: ' . filesize($filepath)); 
    header('Expires: 0'); 
    finfo_close($finfo); 

    ob_clean(); 
    flush(); 
    readfile($filepath); 
    exit; 
} 

回答

0

請使用此方法

$文件收到的完整路徑,文件名$是下載的文件名。

public static function downloadFile($file, $filename) 
    { 
     if (file_exists($file)) { 
      header('Content-Description: File Transfer'); 
      header('Content-Type: application/octet-stream'); 
      header('Content-Disposition: attachment; filename = '.basename($filename)); 
      header('Content-Transfer-Encoding: binary'); 
      header('Expires: 0'); 
      header('Cache-Control: must-revalidate, post-check = 0, pre-check = 0'); 
      header('Pragma: public'); 
      header('Content-Length: ' . filesize($file)); 
      ob_clean(); 
      flush(); 
      readfile($file); 
      die; 
     } 
    } 
+0

嗨佩德羅。謝謝,但這仍然導致同樣的問題。該文件在下載後無法打開。 – ccdavies

+0

在這種情況下,你可能在頭文件之前有一些輸出......就像一個noite或什麼東西,你可以發佈完整的代碼嗎? –