- ZIP в PHP (ZipArchive)
- Добавление файлов в архив
- Заархивировать директорию с содержимым
- Переименовать файл
- Если файл лежит в папке
- Удалить файл из архива
- Если файл лежит в папке
- Список файлов в архиве
- Извлечь весь архив
- Извлечь определенные файлы
- Извлечь файл в поток
- Examples
- User Contributed Notes 5 notes
- How to Zip and Unzip Files in PHP
- Compressing Individual Files in PHP
ZIP в PHP (ZipArchive)
Класс ZipArchive позволяет быстро и удобно работать с ZIP-архивам, рассмотрим основные возможности класса.
Добавление файлов в архив
В примере используются константы:
- ZipArchive::CREATE – создавать архив, если он не существует
- ZipArchive::OVERWRITE – если архив существует, то игнорировать текущее его содержимое т.е. работать как с пустым архивом.
$zip = new ZipArchive(); $zip->open(__DIR__ . '/archive.zip', ZipArchive::CREATE|ZipArchive::OVERWRITE); $zip->addFile(__DIR__ . '/image1.jpg', 'image1.jpg'); $zip->addFile(__DIR__ . '/image2.jpg', 'image2.jpg'); $zip->close();
Если файл необходимо поместить в директорию, то предварительно не нужно создавать пустую папку. Можно просто указать путь и имя файла, например «src»:
$zip->addFile(__DIR__ . '/image1.jpg', 'src/image1.jpg'); $zip->addFile(__DIR__ . '/image2.jpg', 'src/image2.jpg');
Если текстовой файл генерится прямо в скрипте, то удобней скинуть его в архив методом addFromString() .
$contents = 'Содержание файла file.log'; $zip = new ZipArchive(); $zip->open(__DIR__ . '/archive.zip', ZipArchive::CREATE|ZipArchive::OVERWRITE); $zip->addFromString('file.log', $contents); $zip->close();
Заархивировать директорию с содержимым
Сделать архив сайта можно с помощью рекурсивной функции, функция обойдет все файлы в директориях и добавит их в архив.
function addFileRecursion($zip, $dir, $start = '') < if (empty($start)) < $start = $dir; >if ($objs = glob($dir . '/*')) < foreach($objs as $obj) < if (is_dir($obj)) < addFileRecursion($zip, $obj, $start); >else < $zip->addFile($obj, str_replace(dirname($start) . '/', '', $obj)); > > > > $zip = new ZipArchive(); $zip->open(__DIR__ . '/archive.zip', ZipArchive::CREATE|ZipArchive::OVERWRITE); addFileRecursion($zip, __DIR__ . '/test'); $zip->close();
Переименовать файл
$zip = new ZipArchive(); $zip->open(__DIR__ . '/archive.zip'); $zip->renameName('image2.jpg', 'images.jpg'); $zip->close();
Если файл лежит в папке
$zip->renameName('src/image2.jpg', 'src/images.jpg');
Удалить файл из архива
$zip = new ZipArchive(); $zip->open(__DIR__ . '/archive.zip'); $zip->deleteName('image2.jpg'); $zip->close();
Если файл лежит в папке
$zip->deleteName('src/image2.jpg');
Список файлов в архиве
$zip = new ZipArchive(); $zip->open(__DIR__ . '/archive.zip'); $i = 0; $list = array(); while($name = $zip->getNameIndex($i)) < $list[$i] = $name; $i++; >print_r($list); $zip->close();
Array ( [0] => src/image1.jpg [1] => src/image2.jpg [2] => file.log )
Извлечь весь архив
$zip = new ZipArchive(); $zip->open(__DIR__ . '/archive.zip'); $zip->extractTo(__DIR__); $zip->close();
Извлечь определенные файлы
$zip = new ZipArchive(); $zip->open(__DIR__ . '/archive.zip'); $zip->extractTo(__DIR__, array('src/image1.jpg', 'src/image2.jpg')); $zip->close();
Извлечь файл в поток
Данный метод удобен если требуется только прочитать содержимое файла.
$zip = new ZipArchive(); $zip->open(__DIR__ . '/archive.zip'); $contents = ''; $fp = $zip->getStream('file.log'); while (!feof($fp)) < $contents .= fread($fp, 2); >fclose($fp); echo $contents; $zip->close();
Examples
$zip -> addFromString ( «testfilephp.txt» . time (), «#1 This is a test string added as testfilephp.txt.\n» );
$zip -> addFromString ( «testfilephp2.txt» . time (), «#2 This is a test string added as testfilephp2.txt.\n» );
$zip -> addFile ( $thisdir . «/too.php» , «/testfromfile.php» );
echo «numfiles: » . $zip -> numFiles . «\n» ;
echo «status:» . $zip -> status . «\n» ;
$zip -> close ();
?>
Example #2 Dump the archive details and listing
$za -> open ( ‘test_with_comment.zip’ );
print_r ( $za );
var_dump ( $za );
echo «numFiles: » . $za -> numFiles . «\n» ;
echo «status: » . $za -> status . «\n» ;
echo «statusSys: » . $za -> statusSys . «\n» ;
echo «filename: » . $za -> filename . «\n» ;
echo «comment: » . $za -> comment . «\n» ;
for ( $i = 0 ; $i < $za ->numFiles ; $i ++) echo «index: $i \n» ;
print_r ( $za -> statIndex ( $i ));
>
echo «numFile:» . $za -> numFiles . «\n» ;
?>
Example #3 Zip stream wrapper, read an OpenOffice meta info
$reader -> open ( ‘zip://’ . dirname ( __FILE__ ) . ‘/test.odt#meta.xml’ );
$odt_meta = array();
while ( $reader -> read ()) if ( $reader -> nodeType == XMLREADER :: ELEMENT ) $elm = $reader -> name ;
> else if ( $reader -> nodeType == XMLREADER :: END_ELEMENT && $reader -> name == ‘office:meta’ ) break;
>
if (! trim ( $reader -> value )) continue;
>
$odt_meta [ $elm ] = $reader -> value ;
>
>
print_r ( $odt_meta );
?>
This example uses the old API (PHP 4), it opens a ZIP file archive, reads each file in the archive and prints out its contents. The test2.zip archive used in this example is one of the test archives in the ZZIPlib source distribution.
Example #4 Zip Usage Example
$zip = zip_open ( «/tmp/test2.zip» );
if ( $zip ) while ( $zip_entry = zip_read ( $zip )) echo «Name: » . zip_entry_name ( $zip_entry ) . «\n» ;
echo «Actual Filesize: » . zip_entry_filesize ( $zip_entry ) . «\n» ;
echo «Compressed Size: » . zip_entry_compressedsize ( $zip_entry ) . «\n» ;
echo «Compression Method: » . zip_entry_compressionmethod ( $zip_entry ) . «\n» ;
if ( zip_entry_open ( $zip , $zip_entry , «r» )) echo «File Contents:\n» ;
$buf = zip_entry_read ( $zip_entry , zip_entry_filesize ( $zip_entry ));
echo » $buf \n» ;
zip_entry_close ( $zip_entry );
>
echo «\n» ;
User Contributed Notes 5 notes
All these examples will not work if the php script has no write access within the folder.
Although you may say this is obvious, I found that in this case, $zip->open(«name», ZIPARCHIVE::CREATE) doesn’t return an error as it might not try to access the file system but rather allocates memory.
It is only $zip->close() that returns the error. This might cause you seeking at the wrong end.
you can use this code for reading JAR files (java archives)
JAR files use the same ZIP format, so can be easily read
$zf = zip_open(realpath(‘D:/lucene/allinone/lucene-core.jar’)); $i=1;
while($zf && $ze = zip_read($zf)) $zi[$i][‘zip entry name’]= zip_entry_name($ze);
$zi[$i][‘zip entry filesize’]= zip_entry_filesize($ze);
$zi[$i][‘zip entry compressed size’]= zip_entry_compressedsize($ze);
$zi[$i][‘zip entry compression method’]= zip_entry_compressionmethod($ze);
$zi[$i][‘zip entry open status’] = zip_entry_open($zf,$ze);
//$zi[$i][‘zip entry file contents’] = zip_entry_read($ze,100);
$i++;
>
print_r($zi);
zip_close($zf);
$zip = new ZipArchive ;
$zip -> open ( ‘teste.zip’ );
$zip -> extractTo ( ‘./’ );
$zip -> close ();
echo «Ok!» ;
?>?php>
1) If you want to add files to a ZIP archive but you don’t know if the ZiP file exists or not, you MUST check: this changes the way you open it !.
2) you can not append multiple flags, can use only one (or none).
If the zip does not exists, open it with:
$ziph->open($archiveFile, ZIPARCHIVE::CM_PKWARE_IMPLODE)
(or a different compression method)
If the zip already exists, open it with:
$ziph->open($archiveFile)
or
$ziph->open($archiveFile, ZIPARCHIVE::CHECKCONS)
Example: make backup files every hour and ZIP them all in a daily ZIP archive, so you want to get only one ZIP per day, each ZIP containing 24 files:
function archivebackup ( $archiveFile , $file , & $errMsg )
$ziph = new ZipArchive ();
if( file_exists ( $archiveFile ))
if( $ziph -> open ( $archiveFile , ZIPARCHIVE :: CHECKCONS ) !== TRUE )
$errMsg = «Unable to Open $archiveFile » ;
return 1 ;
>
>
else
if( $ziph -> open ( $archiveFile , ZIPARCHIVE :: CM_PKWARE_IMPLODE ) !== TRUE )
$errMsg = «Could not Create $archiveFile » ;
return 1 ;
>
>
if(! $ziph -> addFile ( $file ))
$errMsg = «error archiving $file in $archiveFile » ;
return 2 ;
>
$ziph -> close ();
If you find your zip file not being created make sure every file you are adding to the zip is valid. If even one file is not available when zip->close is called then the archive will fail and your zip file won’t be created.
How to Zip and Unzip Files in PHP
Monty Shokeen Last updated Jun 13, 2022
Compressing files when transferring them over the internet has a lot of advantages. In most cases, the combined total size of all the files in the compressed format comes down by a nice margin. This means that you will save some of your bandwidth, and users will also get faster download speeds. Once the users have downloaded a file, they can decompress it whenever they want. In short, compression can make serving files over the internet a lot easier for you as well as your visitors.
One factor that can discourage you from compressing files or make the process very tiresome is the fact that you might be doing it manually. Luckily, PHP comes with a lot of extensions that deal specifically with file compression and extraction. You can use the functions available in these extensions to automatically compress files in PHP.
This tutorial will teach you how to zip and unzip (compress and extract) files to and from a zip archive in PHP. You will also learn how to delete or rename files in an archive without extracting them first.
Compressing Individual Files in PHP
The PHP ZipArchive class has a lot of properties and methods which can help you compress and decompress all your files.
You can add files to your zip archive one at a time or add the whole directory at once. In either case, the first step is to create a new ZipArchive instance and then call the open($filename, [$flags]) method. This method will open a new zip archive for reading, writing, or other modifications. There are five valid values for the optional $flag parameter which determine how to handle different situations.
- ZipArchive::OVERWRITE —This flag will overwrite the contents in the specified archive if it already exists.
- ZipArchive::CREATE —This flag will create a new archive if it does not already exist.
- ZipArchive::EXCL —This flag will result in an error if the archive already exists.
- ZipArchive::CHECKCONS —This flag will tell PHP to perform additional consistency checks on the archive and give an error if they fail.
- ZipArchive::RDONLY —This flag became available in PHP 7.4.3 and allows you to open an archive in read-only mode.
You can check the documentation of this method to learn about different error codes returned in case of failures to open the file. If the zip file was opened or created successfully, the method will return true .
You will have to use different flag combinations in different situations to avoid any unexpected results. For example, use the ZipArchive::OVERWRITE flag if you don’t care about the content of an existing archive. It will not create a new archive if none exists with that particular name.
You can use a combination of ZipArchive::OVERWRITE and ZipArchive::CREATE to overwrite an existing archive and create a new archive if none exists with that particular name. Here’s an example:
$zip->open('my_compressed_files.zip', ZipArchive::OVERWRITE|ZipArchive::CREATE);
When using the ZipArchive::CREATE flag, you will notice that it starts modifying an existing archive if one already exists. This might be what you actually want to do, but it can also have some unexpected consequences. You can use a combination of ZipArchive::CREATE and ZipArchive::EXCL to make sure that you are only working with archives that did not previously exist.
$zip->open('new_compressed_files.zip', ZipArchive::EXCL|ZipArchive::CREATE);
Once you have opened the archive successfully, you can use the addFile($filename, $localname, $start, $length) method to add any file from a given path to your archive. The $filename parameter is the path of a file that you want to add to the archive. The $localname parameter is used to assign a name to the file to store it inside the archive. You can call addFile() every time you want to add a new file to your archive.
After adding all the necessary files to the archive, you can simply call the close() method to close it and save the changes.
Let’s say you have a website which allows users to download font files for different fonts along with the licensing information to use them. Files like these will be perfect examples of automated archiving using PHP. The following code shows you how to do exactly that.