Home>Article>Backend Development> How to compress a directory in PHP? (code example)
In PHP we can use the ZipArchive class to compress and decompress directories and create ZIP files. The following article will give you a brief understanding of how to use the ZipArchive class to create compressed files. I hope it will be helpful to you.
PHP ZipArchive Class
PHP ZipArchive class can be used for compression and decompression. If it doesn't exist, you may need to install the class.
Starting with PHP 5.3, this extension is built-in. Prior to this, Windows users needed to enable php_zip.dll in php.ini to use its functionality.
Steps:
1. Open the php.ini file and add
extension=php_zip.dll
2. After saving, restart Apache or other servers.
Code examples for using the ZipArchive class
Let’s take a look at how to use the ZipArchive class through code examples.
Example 1:Use the ZipArchive class and create a compressed file
open($zipcreated, ZipArchive::CREATE ) === TRUE) { // 将路径存储到变量中 $dir = opendir($pathdir); while($file = readdir($dir)) { if(is_file($pathdir.$file)) { $zip -> addFile($pathdir.$file, $file); } } $zip ->close(); } ?>
The original directory without compression:
Compressed directory:
##Example 2:Use the ZipArchive class to decompress files or directories
open('demo/article.zip'); // 解压目录 $zip->extractTo('./demo/'); $zip->close(); ?>The above is the entire content of this article, I hope it will be helpful to everyone's study. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How to compress a directory in PHP? (code example). For more information, please follow other related articles on the PHP Chinese website!