How to create zip file using 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.
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('test_new.zip', ZipArchive::CREATE) === TRUE) { // 将文件添加到zip文件 $zip->addFile('test.txt'); $zip->addFile('test.pdf'); // 将random.txt文件添加到zip并将其重命名为newfile.txt $zip->addFile('random.txt', 'newfile.txt'); // 将有指定文本的new.txt文件添加到zip文件中 $zip->addFromString('new.txt', '要添加到new.txt文件中的文本'); // 关闭zip文件 $zip->close(); } ?>
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('test_overwrite.zip', ZipArchive::OVERWRITE) === TRUE) { // 将文件添加到zip文件 $zip->addFile('test.txt'); $zip->addFile('test.pdf'); // 关闭zip文件 $zip->close(); } ?>
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('test_folder.zip', ZipArchive::CREATE) === TRUE) { // 将文件添加到zip文件中的demo_folder文件夹内 $zip->addFile('text.txt', 'demo_folder/test.txt'); $zip->addFile('test.pdf', 'demo_folder/test.pdf'); // 将random.txt文件添加到zip文件中的demo_folder文件夹内,并重命名为newfile.txt $zip->addFile('random.txt', 'demo_folder/newfile.txt'); // 将有指定内容的new.txt添加到zip文件中的demo_folder文件夹 $zip->addFromString('demo_folder/new.txt', '要添加到new.txt文件中的文本'); // 关闭zip文件 $zip->close(); } ?>
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('test_folder_change.zip', ZipArchive::CREATE) === TRUE) { // 将文件添加到zip文件 $zip->addFile('text.txt', 'demo_folder/test.txt'); $zip->addFile('test.pdf', 'demo_folder1/test.pdf'); // 关闭zip文件 $zip->close(); } ?>
##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 folderCreate a zip file containing all files in a directory
<?php $zip = new ZipArchive; if ($zip->open('test_dir.zip', ZipArchive::OVERWRITE) === TRUE) { if ($handle = opendir('demo_folder')) { // 添加目录中的所有文件 while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != ".." && !is_dir('demo_folder/' . $entry)) { $zip->addFile('demo_folder/' . $entry); } } closedir($handle); } $zip->close(); } ?>
Code Description
Chapter 5- Line 16: Open a directory and create a zip file containing all the files in the directoryLine 5: Open the directoryLine 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 directoryLine 18: Close zip fileCreate 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('test_files_dirs.zip', ZipArchive::OVERWRITE) === TRUE) { // 添加 directory1 if ($handle = opendir('demo_folder/directory1/')) { while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != "..") { $zip->addFile('demo_folder/directory1/' . $entry); } } closedir($handle); } // 添加 directory2 if ($handle = opendir('demo_folder/directory2/')) { while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != "..") { $zip->addFile('demo_folder/directory2/' . $entry); } } closedir($handle); } // 添加 directory3 if ($handle = opendir('demo_folder/directory3/')) { while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != "..") { $zip->addFile('demo_folder/directory3/' . $entry); } } closedir($handle); } $zip->close(); } ?>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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

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,

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

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

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 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.
