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

青灯夜游
Release: 2023-04-05 16:14:01
Original
4553 people have browsed it

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
Copy after login

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

<?php 
  
// 需要压缩的目录名
$pathdir = "demo/";  
  
// 创建压缩目录的名称
$zipcreated = "Zip.zip"; 
  
// 创建新的zip类
$zip = new ZipArchive; 
   
if($zip -> open($zipcreated, ZipArchive::CREATE ) === TRUE) { 
      
    // 将路径存储到变量中
    $dir = opendir($pathdir); 
       
    while($file = readdir($dir)) { 
        if(is_file($pathdir.$file)) { 
            $zip -> addFile($pathdir.$file, $file); 
        } 
    } 
    $zip ->close(); 
} 
  
?>
Copy after login

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

<?php 
  
// 创建新的zip类
$zip = new ZipArchive; 
  
// 添加需要解压缩的zip文件名
$zip->open(&#39;demo/article.zip&#39;); 
  
// 解压目录
$zip->extractTo(&#39;./demo/&#39;); 
  
$zip->close();  
  
?>
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template