Home>Article>Backend Development> How to compress a directory in PHP? (code example)

How to compress a directory in PHP? (code example)

青灯夜游
青灯夜游 Original
2019-03-15 18:04:23 4373browse

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.

How to compress a directory in PHP? (code example)

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:

How to compress a directory in PHP? (code example)

Compressed directory:

How to compress a directory in PHP? (code example)

How to compress a directory in PHP? (code example)

##Example 2:Use the ZipArchive class to decompress files or directories

open('demo/article.zip'); // 解压目录 $zip->extractTo('./demo/'); $zip->close(); ?>

How to compress a directory in PHP? (code example)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn