2012-07-14 89 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