Hướng dẫn php zip->addfile

zip là một định dạng nén phổ biến, được sử dụng để làm giảm dung lượng các định dạng file, để có thể dễ dàng gửi chúng đi nơi khác. PHP sử dụng class ZipArchive để hỗ trợ nén một hoặc nhiều file tới một file zip.
ZipArchive là class built-in của PHP nên bạn có thể dễ dàng gọi chúng mà không phải thực hiện bất cứ một cài đặt gì.

Zip 1 file



Notes

Note:

When a file is set to be added to the archive, PHP will lock the file. The lock is only released once the ZipArchive object has been closed, either via ZipArchive::close[] or the ZipArchive object being destroyed. This may prevent you from being able to delete the file being added until after the lock has been released.

jayarjo

12 years ago

It is not obvious, since there are no noticeable examples around, but you can use $localname [second parameter] to define and control file/directory structure inside the zip. Use it if you do not want files to be included with their absolute directory tree.

john factorial

11 years ago

Beware: calling $zip->addFile[] on a file that doesn't exist will succeed and return TRUE, delaying the failure until you make the final $zip->close[] call, which will return FALSE and potentially leave you scratching your head.

If you're adding multiple files to a zip and your $zip->close[] call is returning FALSE, ensure that all the files you added actually exist.

It's also a good idea to check each file with file_exists[] or is_readable[] before calling $zip->addFile[] on it.

aartdebruijn at gmail dot com

11 years ago

When adding a file to your zip, the file is opened and stays open.
When adding over 1024 files [depending on your open files limit] the server stops adding files, resulting in a status 11 in your zip Archive. There is no warning when exceeding this open files limit with addFiles.

Check your open files with ulimit -a

This kept me busy for some time.

frame86 at live dot com

8 years ago

The manual is lying.

"In short, it means you can first delete an added file after the archive is closed. "

Thats true but not by locking the file...
Warning! This method works asynchronous!

It seems that addFile[] will return TRUE if the file stat command returns correctly, but the operation itself will not happen yet.

Instead, deleting a file is always possible. I have discovered this behaviour by using a temporary file and deleting it immediately after addFile[] returns. The result was that no archive was created nor any file was added although every operation [creating,open[],addFile[]] returned true before. The operation silenty fails.

romuloum at hotmail dot com

8 years ago

If you have problem with windows explorer reading zipfile created by linux, try:
$oZip->addFile [ $file_name, " " . basename [ $file_name ] ]
That space " " should solve.

wacher at freemail dot hu

14 years ago

The workaround above [file_get_contents] is very dangerous if you pack large files. [see memory limit].
Close/open the zip archive periodically instead of using file_get_contents[].

garcia at no_span dot krautzer-lynn dot com

13 years ago

If you add files that have an absolut path, like for example:
/mnt/repository/my_file.pdf
the standard windows zip utility will not be able to extract the files. The first slash trips the zip utility. You have to add relative file paths or use a symbolic link.

camuc at camuc dot net

12 years ago

In some versions of this library you NEED to add the "localfile" parameter or the file will not show in the Zip folder.

peter at boring dot ch

13 years ago

Here's a little extension to ZipArchive that handles directories recursively:

kris at blacksuitmedia [do/t/] c0m

9 years ago

I had a huge number of files and folders that I needed to zip on a linux web server. I was running into timeout problems and file enumerator issues, as well as file handler limit issues [ulimit]. I used a script to solve u limit offered by Farzad Ghanei first [ZipArchiveImproved], but closing and reopening his way didn't do the trick for me.

I eventually did a simple call to a $filelimit variable I created that records file handler limit I want my script to hit before it closes and reopens the file.


This made some progress for me, timeouts were gone, but when calling

after the reopening of the Zip, I got an error. I echoed the and found that after reopening, the numFile enum reset to '0'.

A few more goose-chases later, I tried addFromString with some better results, but did not get it working 100% until I actually coupled addFromString with addFile! My working scripting for the add files function on massive file-folder structures looks like so:


I hope this may help someone else.

Anonymous

12 years ago

On my system [Windows], I found that ZipArchive uses IBM850 encoding for filenames [localname]. For filenames with special characters such as [é] é which appears at 0xE9 in the ISO-8859-1, it is at 0x82 in IBM850. I had to call iconv['ISO-8859-1', 'IBM850', 'Québec'] to get correct file names.

ohcc at 163 dot com

6 years ago

Do NOT use ZipArchive::addFile[] to append a folder.

When a folder's path is passed to ZipArchive::addFile[], the method returns true, but ZipArchive can neither create a zip archive nor can it make any change to a existing file.

sp at read dot eu

10 years ago

Note that using addFile[] will change the order of the files within the zip, in fact within the index of the zip. Does not matter much, except if you loop the index and use addFile[] within that loop : it will likely give messy results.

Example :


This code may loop for ever, depending on your forsomereason[] function, or at least you're at risk.

Try something like this instead :



Hope it helps ;-]

610010559 at qq dot com

6 months ago

there are some points  can be more clear, it take me some time to figure out. hope it can help you.
1.use addFile[] ,method to add the file with path to zip. if the directory not exist, addFile[] would auto create it.


2. addFile[] would overwrite the old file if exist in default.

stanislav dot eckert at vizson dot de

7 years ago

2 tips:

- The example in on this page is a bit misleading for new programmers. It works only if the ZIP archive file exists already. Don't forget to use ZipArchive::CREATE and optionally ZipArchive::OVERWRITE in the second optional parameter in the open[] function.

- If you want to add files and directories recursively [see some examples from other comments here on this page] use scandir[] instead of blob[] because blob[] does not list hidden files like ".htaccess" for example.

raja at rsdisk dot com

3 years ago

zip->addfile function does not add file to archive immediately. It is cued and executed at zip->close[]

I had backup files in a dir. with a foreach statement I was adding the file to an archive and then moving the files into dump dir immediately.

This caused an error.



The $zip->close[] needs to execute before moving files,

gio AT giombg dot com

4 years ago

work 4 me

$zip = new ZipArchive;
$zip_name = ['name.zip'];
$path_zip = [$config['path'].'/zip/'.$zip_name];
$zip->open[$path_zip,ZipArchive::CREATE];
$zip->addFile[$path2.'/'.$nam1,$nam1];
$zip->addFile[$path2.'/'.$nam2,$nam2];
$zip->close[];

ciao
GioMBG

christophe dot braud at aquafadas dot com

13 years ago

If you have some warnings with ZipArchiveImproved since the last Ubuntu update, replace "self::CREATE" by "self::CREATE | self::OVERWRITE" in the reopen function

christophe

Farzad Ghanei

13 years ago

here is a basic class that extends the ZipArchive to:
  * add a functionality to report the ZIP file address [I needed it and I could not find out how in ZipArchive documentation].
  * resolve the problem of adding so many files to the archive due file descriptor limit. the ZipArchiveImproved::addFile[] handles this.

todd at toddwiggins dot com dot au

8 years ago

The addFile[] method does not accept the "file://" protocol. Strip away "file://" and use the absolute path instead.

I assume that it also does not accept any other protocols, I was having issues trying to add files, other functions within the application I was building required the use of the protocol.

Also to note, the status code returned did not match any of the predefined error codes, and the status code was never the same. My assumption was a overflow on the variable as the status codes were around the minimum and maximum INT values.

s dot eckert dot spam at gmx dot com

8 years ago

Note that there is no concept of "folders" for ZIP files. If you need to store data into folders, use forward slashes ["/"] in $localname to separate folder[s] and the file name.

Example:
$zip->addFile["test.txt", "mainfolder/subfolder/test.txt"];

Dean Rather

9 years ago

This add directory function does not require that you create a new wrapper class, and also does not add the entire file directory tree into your zip file.

shano

10 years ago

thought it might come in handy
recursively adds all directories and files within a directory

class zip extends ZipArchive {

        public function addDirectory[$dir] { // adds directory
        foreach[glob[$dir . '/*'] as $file] {
            if[is_dir[$file]]
                $this->addDirectory[$file];
            else
                $this->addFile[$file];
        }
    }
}

Andreas R. newsgroups2005 at geekmail de

15 years ago

Currently the number of files that can be added using addFile to the ZIP archive [until it is closed] is limited by file descriptors limit. This is an easy workaround [on the bug links below you can find another workarounds]:

ptipti at gala dot net

10 years ago

Another surprise, which took a lot of trouble. So that after you add a file to the archive it can be safely removed, took advantage of such construction:

if [!is_file [$archive]] :
    $result = $zip->open [$archive, ZipArchive::CREATE];
else :
    $result = $zip->open [$archive];
endif;
if [$result === TRUE] :
    if [[$zip->addFile [$file, $filename]] === TRUE] :
        $theoreticaly_added = TRUE;
    endif;
    if [[[$zip->close []] === TRUE] && $theoreticaly_added] :
        unlink [$file];
    endif;
endif;

Now the files will not disappear. But perhaps there is a simpler solution, which gives 100% guarantee?

javierseixas at gmail dt com

14 years ago

I have had several problems trying adding files, because of a path problem. The error gived was this:

ZipArchive::addFile[] [function.ZipArchive-addFile]: Unable to access

I used an absolute root starting by "/", and it didn't work. Try starting your path with "./" [referencing the root of your site].

ohcc at 163 dot com

6 years ago

如果文件名包含汉字,ZIPARCHIVE::addFile[] 会导致无法将文件压缩到压缩包中,或者压缩以后文件名乱码。

可以使用ZipArchive::addFromString[]来实现。

注意:如果操作系统是Windows,文件系统编码是gbk.
如果php文件的文件编码是utf-8,需要相应转码。

ZipArchive::addFile[] fails if the filename contains Chinese characters.

ZipArchive::addFromString[] should be used instead.



Hope it helps someone.

pelpet at ic dot cz

12 years ago



What I have to do, when I wan't to have the file in the zip archive with it's name before archiving?
[Sorry, I'm from Czech Republic and I can't speak English very well, if I did anywhere mistake, so ignore that pease :-]

Chủ Đề