Zip and Unzip Files in PHP Tutorial
Embark on a journey with us as we explore the methods of File Compression and Extraction (Zip/Unzip) in the PHP programming language. This tutorial is primarily created for students and new PHP programmers and serves as a valuable reference to elevate your understanding and skills. Along the way, you'll find illustrative sample snippets showcasing the compression and extraction of files (Zip/UnZip) using PHP.
What is Zip and UnZip?
Zip
is the process of compressing files or folders into a unified archive, typically utilizing the ZIP file format. This compression method serves to significantly reduce file sizes, making them more manageable and facilitating seamless transmission over the internet.
UnZip
, on the other hand, involves the extraction or decompression of files and folders from a compressed archive. In essence, UnZip
is the reverse process of Zip.
Within the realm of software and web application development, the incorporation of Zip and Unzip functionality emerges as a highly valuable feature. This implementation elevates efficiency, enhances organization, and contributes to an improved user experience when managing digital files, establishing it as an indispensable capability.
Outlined below are key reasons driving the adoption of this feature:
- Efficient Compression: Streamlining file size for improved data management.
- Optimized Storage Space: Reducing the required storage footprint.
- Backup and Recovery: Facilitating seamless data backup and retrieval processes.
- Enhanced File Organization: Structuring files for better management and retrieval.
- Accelerated Downloads: Expediting the transfer of files for improved user experience.
Here are some other tutorial that are related to Compressed Files in PHP:
- Export MySQL Data to CSV and Download It as a ZIP File
- Compressing Multiple Files as Zip and Download it
How to Zip and Unzip File in PHP?
PHP boasts a handy class known as ZipArchive
. This class is specifically crafted with powerful methods to facilitate the creation, modification, and extraction of ZIP files. With ZipArchive
, developers can seamlessly integrate ZIP file functionalities into their PHP applications.
To unleash the capabilities of ZipArchive
in your PHP environment, ensure that the zip
extension in your php.ini
file is enabaled. Simply locate the line containing ;extension=zip
, remove the semi-colon to enable it, and don't forget to restart your Apache server after making these changes.
Then you can check the zip status using the phpinfo()
.
Creating or Modifying Zip File
To create or modify a compressed ZIP file, the open()
method within the ZipArchive
class comes into play. This method is dessinged to open a new or existing zip file, allowing for reading, writing, or modification. It's crucial to pair the open()
method with the close()
method, designed to finalize the opened or created archive and save any changes made.
The open()
method necessitates two arguments: the filename
as the first argument and flags
as the second argument.
Here are the various flags available for use in the open()
method:
- ZipArchive::CHECKCONS - Performs consistency checks on the archive and triggers errors if they fail.
- ZipArchive::CREATE - Creates the archive file if it doesn't already exist.
- ZipArchive::EXCL - Returns an error if the archive already exists.
- ZipArchive::OVERWRITE - Overwrites the existing archive and treats it as an empty archive.
- ZipArchive::RDONLY - Opens the archive in read-only mode.
- <?php
- $zip = new ZipArchive();
- $zip->open('sample_compressed.zip', ZipArchive::OVERWRITE|ZipArchive::CREATE);
- $zip->close();
- ?>
Adding Files in Archive
ZipArchive
comes with a method known as addFile()
. This method is designed to add a file in a Zip file from the given path. Here's an example snippet that demonstrate the usage of this method:
- <?php
- try{
- // Open ZipArchive
- $zip = new ZipArchive();
- // Create Compressed file if Exists, otherwise Overwrite
- if($zip->open('sample_compressed.zip', ZipArchive::OVERWRITE|ZipArchive::CREATE) !== TRUE){
- }
- /**
- * Creating a sample files to add in Archive
- */
- }
- }
- $zip->addFile('./file_101.txt', 'file_101.txt');
- $zip->addFile('./file_102.txt', 'file_102.txt');
- $zip->close();
- echo "Zip file has been created successfully.";
- }catch(Exception $e){
- echo "Creating the compressed file failed.\n";
- }
- ?>
In the code snippet provided, we showcase the generation of two distinct .txt
files, automatically generated if they do not exist. These files are subsequently included and compressed into an archive (zip) file, the output of which is shown in the accompanying image.
Adding Files with Directories in Archive
In addition to individual files, a compressed ZIP file has the capability to include both files and folders. The ZipArchive
provides a useful method called addGlob()
, specifically designed to incorporate files from a directory based on a glob pattern. By utilizing addGlob()
, one can seamlessly add the contents of a folder to a designated directory within the archive. Refer to the code snippet below for guidance on implementing this method:
- <?php
- try{
- // Open ZipArchive
- $zip = new ZipArchive();
- // Create Compressed file if Exists, otherwise Overwrite
- if($zip->open('sample_compressed.zip', ZipArchive::OVERWRITE|ZipArchive::CREATE) !== TRUE){
- }
- /**
- * Creating a sample files to add in Archive
- */
- }
- }
- // Adding files in archive root
- $zip->addFile('./file_101.txt', 'file_101.txt');
- $zip->addFile('./file_102.txt', 'file_102.txt');
- /**
- * Creating a directory to insert in Archive
- */
- }
- }
- // Adding directories and its files in archive file
- $zip->addGlob("./dir_101/*", 0, [ "add_path" => "dir_101/", "remove_all_path" => TRUE ]);
- $zip->addGlob("./dir_102/*", 0, [ "add_path" => "dir_102/", "remove_all_path" => TRUE ]);
- $zip->close();
- echo "Zip file has been created successfully.";
- }catch(Exception $e){
- echo "Creating the compressed file failed.\n";
- }
- ?>
In the code snippet above, observe that the addGlob()
method consists of three arguments. The first is the pattern
, followed by the flag
(a bit mask derived from a glob()
mask), and finally, the option
(an array of options for adding the file or files).
The pattern
argument denotes the path of the files to be added to the archive, with a specified pattern for allowable file names and extensions. The add_path
option is used to include a folder in the archive where the files will be stored. Additionally, the remove_all_path
option is set to TRUE
, ensuring the removal of all paths during the process.
As the result of the PHP script provided above, refer to the following image:
Adding Files with Multiple Child Directories in Archive
When adding files with multiple nested directories to a compressed file, it's essential to devise a straightforward function that compiles or enumerates all the paths of child directories within the parent folder. This ensures the correct identification of each folder, mimicking the structure of the original uncompressed folder and files. Below is an example PHP snippet that illustrates this procedure:
- <?php
- /**
- * List all child directories
- */
- function get_directories($directory){
- $dir_names = [];
- foreach($scannedDir as $name){
- $dir_names[] = $directory."/".$name;
- }
- }
- }
- return [];
- }
- try{
- $multi_dir_path = "dir_101";
- // Open ZipArchive
- $zip = new ZipArchive();
- // Create Compressed file if Exists, otherwise Overwrite
- if($zip->open('sample_compressed.zip', ZipArchive::OVERWRITE|ZipArchive::CREATE) !== TRUE){
- }
- $zip->addGlob("{$multi_dir_path}/*.*", 0, [ "add_to_path" => "{$multi_dir_path}/" ]);
- /**
- * List All directories inside the selected path
- */
- foreach($scannedDir as $name){
- $dir_names[] = $multi_dir_path."/".$name;
- }
- }
- // Adding directories files into the archive
- foreach($dir_names as $dir){
- $zip->addGlob("{$dir}/*.*", 0, [ "add_to_path" => "{$dir}/" ]);
- }
- }
- $zip->close();
- echo "Zip file has been created successfully.";
- }else{
- echo "Selected Directory does not exists.";
- }
- }catch(Exception $e){
- echo "Creating the compressed file failed.\n";
- }
- ?>
Extracting the Compressed File
The ZipArchive
class provides the functionality to extract compressed files. One of its key methods for this purpose is extractTo()
. Specifically crafted for extracting compressed files, this method facilitates the conversion of compressed content into an uncompressed state within a designated directory.
Here's the following snippet that demonstrate usage of uncompressing all the files and folders of a compressed file:
- <?php
- try{
- // Open ZipArchive
- $zip = new ZipArchive();
- // Create Compressed file if Exists, otherwise Overwrite
- if($zip->open('sample_compressed.zip', ZipArchive::CREATE) !== TRUE){
- }
- $zip->extractTo("uncompressed");
- $zip->close();
- echo "Zip file has been extracted successfully.";
- }catch(Exception $e){
- echo "Extracting the compressed file failed.\n";
- }
- ?>
Here's the following snippet that demonstrates the usage of uncompressing only the selected files and folders of a compressed file:
- <?php
- try{
- // Open ZipArchive
- $zip = new ZipArchive();
- // Create Compressed file if Exists, otherwise Overwrite
- if($zip->open('sample_compressed.zip', ZipArchive::CREATE) !== TRUE){
- }
- $zip->extractTo("uncompressed", ["dir_101/file_101.txt", "file_102.txt"]);
- $zip->close();
- echo "Zip file has been extracted successfully.";
- }catch(Exception $e){
- echo "Extracting the compressed file failed.\n";
- }
- ?>
Conclusion
To sum up, PHP offers a built-in class equipped with essential features and methods that prove highly beneficial for tasks related to the creation, modification, and extraction of compressed files. This class is referred to as ZipArchive
. For practical insights into the utilization of this class in handling compressed files, you can refer to the example snippets provided above.
There you have it! I hope this Zip and Unzip Files in PHP Tutorial will help you with what you are looking for and you'll find this useful for your future PHP projects. Explore more on this website for more Free Source Codes, Tutorials, and Article that covers various programming languages.
Happy Coding =)
Add new comment
- 250 views