2012-07-14 90 views
2

我有一些pdf文件...我只想將它們作爲集合下載,而不是一個一個地下載。 爲此,我想壓縮所有pdf文件並下載。但我不知道爲什麼當我在我的代碼中更改ZipArchive文件名時,它說的是損壞和損壞。 我的代碼如下: -下載由PHP中的多個文件構成的Zip文件

function zipFilesAndDownload($file_names,$archive_file_name,$file_path) 
{ 
    $zip = new ZipArchive(); 
    //create the file and throw the error if unsuccessful 
    if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE)!==TRUE) { 
     exit("cannot open <$archive_file_name>\n"); 
    } 
    //add each files of $file_name array to archive 
    foreach($file_names as $files) 
    { 
     $zip->addFile($file_path.$files,$files); 

    } 
    $zip->close(); 
    //then send the headers to foce download the zip file 
    header("Content-type: application/zip"); 
    header("Content-Disposition: attachment; filename=$archive_file_name"); 
    header("Pragma: no-cache"); 
    header("Expires: 0"); 
    readfile("$archive_file_name"); 
    exit; 
} 



if($button=="Save as pdf") 
{ 
$file_names = array(); 
foreach($a as $key=>$as) 
{ 
$file_names[] = $key.'.pdf'; 
} 
} 
$archive_file_name='zipped.zip'; 
$file_path='/resume/'; 
zipFilesAndDownload($file_names,$archive_file_name,$file_path); 

?> 

有人能幫我嗎?提前致謝。

它的工作正常,但我仍然面臨2個問題,1。如果我將archive_file_name的名稱更改爲上面給出的以外的內容,則會出現「存檔已損壞」的錯誤。我不知道它爲什麼發生2.如果我有一個zip文件,說2個pdf,然後我再次下載一個只有1個pdf的zip文件,這個文件與以前的不一樣。但是當我下載1 pdf的zip文件時,我得到3個pdf文件......我不知道爲什麼........請幫助我。

+0

你試過了哪個名字?哪一個是好的? – j0k 2012-07-14 17:51:16

+0

我已經嘗試過zipper1.zip,它不能正常工作。它只與zipper.zip名稱一起工作。 – hatellla 2012-07-14 19:57:26

回答

1

我測試了zipFilesAndDownload函數,它運行良好。所以起初你應該檢查你的腳本,在<?php開始標記之前是否沒有發送字符或空格。

在你的腳本是一個CMS內運行的情況下,你也應該清楚所有的輸出緩衝器:while (@ob_end_clean());(如果gzip的頭已經發送出去後,還反過來GZ壓縮再次ob_start('ob_gzhandler');

你也可以還要檢查,如果你已正確設置$ FILE_PATH和所有的文件存在,例如:

$file_path='resume/'; 
if (!file_exists($file_path) || !is_dir($file_path)) { 
    die("Invalid directory $file_path in ".getcwd()); 
} 
// you can test the existence of your problematic files: 
foreach ($file_names as $file) { 
    if (!file_exists($file_path.$file)) { 
     echo "$file not found."; 
    } else { 
     echo "$file is ok."; 
    } 
} 
exit; 
// end of test 
zipFilesAndDownload($file_names,$archive_file_name,$file_path); 

在Windows中也使用UTF-16/UTF-8 /國際字符編碼的問題,在這裏看到:PHP detecting filesystem encodingHow do I use filesystem functions in PHP, using UTF-8 strings?

+0

感謝您的回覆。 – hatellla 2012-07-14 19:32:51

+0

其工作正常,但我仍然面臨2個問題,1。如果我將archive_file_name的名稱更改爲上面給出的以外的內容,則會出現「存檔已損壞」的錯誤。我不知道它爲什麼發生2.如果我有一個zip文件,說2個pdf,然後我再次下載一個只有1個pdf的zip文件,這個文件與以前的不一樣。但是當我下載1 pdf的zip文件時,我得到3個pdf文件......我不知道爲什麼........請幫助我。 – hatellla 2012-07-14 19:33:28

+0

嗨,我也不知道爲什麼。但是你可以在一些hexaviewer中檢查壓縮文件,看它是否以PK字母開頭。除此之外,我不知道。 – Stano 2012-07-14 22:33:20