Home Backend Development PHP Tutorial How to create zip file using PHP

How to create zip file using PHP

Feb 15, 2019 am 10:57 AM
php

Using compressed files can save disk space; and compressed files are smaller, convenient for network transmission, and highly efficient. This article introduces how to use PHP to create zip compressed files. I hope it will be helpful to you.

How to create zip file using PHP

In PHP there is a ZipArchive class that can be easily used to create zip files. The following is an example of how to create a zip file in PHP. [Video tutorial recommendation: PHP tutorial]

Create a new zip file

The following code will create a new zip file (test_new.zip) and add some files to it.

<?php
$zip = new ZipArchive;
if ($zip->open(&#39;test_new.zip&#39;, ZipArchive::CREATE) === TRUE)
{
    // 将文件添加到zip文件
    $zip->addFile(&#39;test.txt&#39;);
    $zip->addFile(&#39;test.pdf&#39;);
 
    // 将random.txt文件添加到zip并将其重命名为newfile.txt
    $zip->addFile(&#39;random.txt&#39;, &#39;newfile.txt&#39;);
 
    // 将有指定文本的new.txt文件添加到zip文件中
    $zip->addFromString(&#39;new.txt&#39;, &#39;要添加到new.txt文件中的文本&#39;);
 
    // 关闭zip文件
    $zip->close();
}
?>
Copy after login

How to create zip file using PHP

Code description:

Line 2: Create an object of ZipArchive class

Line 3: Used to create and open a file called test_new.zip so that we can add files to it. The flag ZipArchive::CREATE specifies that we want to create a new zip file

Lines 6 and 7: used to add files to the zip file.

Line 10: Used to add a file named random.txt to the zip file and rename it to newfile.txt in the zip file.

Line 13: Used to add a new file new.txt. The content of the file is "text to be added to the new.txt file".

Line 16: Close and save changes to the zip file.

Note: Sometimes problems can occur when using relative paths to files. If there is any problem using the path, then we can also use the absolute path of the file

Overwrite the existing zip file

If you want to overwrite the existing zip file For zip files, we can use code similar to the following. The flag ZipArchive::OVERWRITE specifies overwriting existing zip files.

<?php
$zip = new ZipArchive;
if ($zip->open(&#39;test_overwrite.zip&#39;, ZipArchive::OVERWRITE) === TRUE)
{
    // 将文件添加到zip文件
    $zip->addFile(&#39;test.txt&#39;);
    $zip->addFile(&#39;test.pdf&#39;);
 
    // 关闭zip文件
    $zip->close();
}
?>
Copy after login

How to create zip file using PHP

Code description

This code will create a file test_overwrite.zip, if the file already exists, the file will be overwritten by this new file.

Create a new zip file and add files in the specified folder

<?php
$zip = new ZipArchive;
if ($zip->open(&#39;test_folder.zip&#39;, ZipArchive::CREATE) === TRUE)
{
    // 将文件添加到zip文件中的demo_folder文件夹内
    $zip->addFile(&#39;text.txt&#39;, &#39;demo_folder/test.txt&#39;);
    $zip->addFile(&#39;test.pdf&#39;, &#39;demo_folder/test.pdf&#39;);
 
    // 将random.txt文件添加到zip文件中的demo_folder文件夹内,并重命名为newfile.txt
    $zip->addFile(&#39;random.txt&#39;, &#39;demo_folder/newfile.txt&#39;);
 
    //  将有指定内容的new.txt添加到zip文件中的demo_folder文件夹
    $zip->addFromString(&#39;demo_folder/new.txt&#39;, &#39;要添加到new.txt文件中的文本&#39;);
 
    // 关闭zip文件
    $zip->close();
}
?>
Copy after login

How to create zip file using PHP

Code description

The above code will add different files in the zip file to the demo_folder folder

The second parameter of the addfile function can be used to store the files in a new file folder

The first parameter in the addFromString function can be used to store the file in a new folder

Create a new zip file and add the file to a different In the folder

<?php
$zip = new ZipArchive;
if ($zip->open(&#39;test_folder_change.zip&#39;, ZipArchive::CREATE) === TRUE)
{
    // 将文件添加到zip文件
    $zip->addFile(&#39;text.txt&#39;, &#39;demo_folder/test.txt&#39;);
    $zip->addFile(&#39;test.pdf&#39;, &#39;demo_folder1/test.pdf&#39;);
 
    // 关闭zip文件
    $zip->close();
}
?>
Copy after login

How to create zip file using PHP

5-How to create zip file using PHP

5-How to create zip file using PHP

##Code Description

We store the test.txt file in the zip file into the demo_folder folder and the test.pdf file into the demo_folder1 folder

Create a zip file containing all files in a directory

<?php
$zip = new ZipArchive;
if ($zip->open(&#39;test_dir.zip&#39;, ZipArchive::OVERWRITE) === TRUE)
{
    if ($handle = opendir(&#39;demo_folder&#39;))
    {
        // 添加目录中的所有文件
        while (false !== ($entry = readdir($handle)))
        {
            if ($entry != "." && $entry != ".." && !is_dir(&#39;demo_folder/&#39; . $entry))
            {
                $zip->addFile(&#39;demo_folder/&#39; . $entry);
            }
        }
        closedir($handle);
    }
 
    $zip->close();
}
?>
Copy after login

How to create zip file using PHP

Code Description

Chapter 5- Line 16: Open a directory and create a zip file containing all the files in the directory

Line 5: Open the directory

Line 8: Get the name of each file in the directory

Line 10: Skip "." and ".." and any other directories

Line 12: Add files to the zip file

Line 15: Close directory

Line 18: Close zip file

Create a zip file containing all files from multiple directories

The following code adds the different folders and files in these directories to the zip file

<?php
$zip = new ZipArchive;
if ($zip->open(&#39;test_files_dirs.zip&#39;, ZipArchive::OVERWRITE) === TRUE)
{
    // 添加 directory1
    if ($handle = opendir(&#39;demo_folder/directory1/&#39;))
    {
        while (false !== ($entry = readdir($handle)))
        {
            if ($entry != "." && $entry != "..")
            {
                $zip->addFile(&#39;demo_folder/directory1/&#39; . $entry);
            }
        }
        closedir($handle);
    }
 
    // 添加 directory2
    if ($handle = opendir(&#39;demo_folder/directory2/&#39;))
    {
        while (false !== ($entry = readdir($handle)))
        {
            if ($entry != "." && $entry != "..")
            {
                $zip->addFile(&#39;demo_folder/directory2/&#39; . $entry);
            }
        }
        closedir($handle);
    }
 
    // 添加 directory3
    if ($handle = opendir(&#39;demo_folder/directory3/&#39;))
    {
        while (false !== ($entry = readdir($handle)))
        {
            if ($entry != "." && $entry != "..")
            {
                $zip->addFile(&#39;demo_folder/directory3/&#39; . $entry);
            }
        }
        closedir($handle);
    }
    $zip->close();
}
?>
Copy after login

How to create zip file using PHP

7-How to create zip file using PHP

7-How to create zip file using PHP

7-How to create zip file using PHP

##Code description

Lines 6-42: Add all files in directories directory1, directory2 and directory3 to the corresponding files in the zip file in the directory.

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 create zip file using PHP. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles