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:

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.

Enabling Zip Extension in PHP INI file

Then you can check the zip status using the phpinfo().

Check Zip Extension if Enabled using 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.

  1. <?php
  2. $zip = new ZipArchive();
  3. $zip->open('sample_compressed.zip', ZipArchive::OVERWRITE|ZipArchive::CREATE);
  4. $zip->close();
  5. ?>

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:

  1. <?php
  2. try{
  3. // Open ZipArchive
  4. $zip = new ZipArchive();
  5. // Create Compressed file if Exists, otherwise Overwrite
  6. if($zip->open('sample_compressed.zip', ZipArchive::OVERWRITE|ZipArchive::CREATE) !== TRUE){
  7. die("An error occurred while creating your zip file");
  8. }
  9.  
  10. /**
  11.   * Creating a sample files to add in Archive
  12.   */
  13. if(!is_file('./file_101.txt')){
  14. file_put_contents('./file_101.txt', "Sample Archive Text file 101");
  15. }
  16. if(!is_file('./file_102.txt')){
  17. file_put_contents('./file_102.txt', "Sample Archive Text file 102");
  18. }
  19.  
  20. $zip->addFile('./file_101.txt', 'file_101.txt');
  21. $zip->addFile('./file_102.txt', 'file_102.txt');
  22.  
  23. $zip->close();
  24. echo "Zip file has been created successfully.";
  25. }catch(Exception $e){
  26. echo "Creating the compressed file failed.\n";
  27. print_r($e->getMessage());
  28. }
  29.  
  30. ?>

Creating a Zip file with files in PHP

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:

  1. <?php
  2. try{
  3. // Open ZipArchive
  4. $zip = new ZipArchive();
  5. // Create Compressed file if Exists, otherwise Overwrite
  6. if($zip->open('sample_compressed.zip', ZipArchive::OVERWRITE|ZipArchive::CREATE) !== TRUE){
  7. die("An error occurred while creating your zip file");
  8. }
  9.  
  10. /**
  11.   * Creating a sample files to add in Archive
  12.   */
  13. if(!is_file('./file_101.txt')){
  14. file_put_contents('./file_101.txt', "Sample Archive Text file 101");
  15. }
  16. if(!is_file('./file_102.txt')){
  17. file_put_contents('./file_102.txt', "Sample Archive Text file 102");
  18. }
  19.  
  20. // Adding files in archive root
  21. $zip->addFile('./file_101.txt', 'file_101.txt');
  22. $zip->addFile('./file_102.txt', 'file_102.txt');
  23.  
  24. /**
  25.   * Creating a directory to insert in Archive
  26.   */
  27. if(!is_dir('./dir_101')){
  28. mkdir('./dir_101');
  29. }
  30. file_put_contents('./dir_101/file_101.txt', "Sample Archive Text file in sample directory 101");
  31.  
  32. if(!is_dir('./dir_102')){
  33. mkdir('./dir_102');
  34. }
  35. file_put_contents('./dir_102/file_102.txt', "Sample Archive Text file in sample directory 102");
  36.  
  37. // Adding directories and its files in archive file
  38. $zip->addGlob("./dir_101/*", 0, [ "add_path" => "dir_101/", "remove_all_path" => TRUE ]);
  39. $zip->addGlob("./dir_102/*", 0, [ "add_path" => "dir_102/", "remove_all_path" => TRUE ]);
  40.  
  41. $zip->close();
  42. echo "Zip file has been created successfully.";
  43. }catch(Exception $e){
  44. echo "Creating the compressed file failed.\n";
  45. print_r($e->getMessage());
  46. }
  47.  
  48. ?>

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:

Creating a Zip file with files and folder in PHP

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:

  1. <?php
  2. /**
  3.   * List all child directories
  4.   */
  5. function get_directories($directory){
  6.  
  7. if(is_dir($directory)){
  8. $dir_names = [];
  9. $scannedDir = scandir($directory);
  10. foreach($scannedDir as $name){
  11. if(!in_array($name, ['.', '..']) && is_dir($directory."/".$name)){
  12. $dir_names[] = $directory."/".$name;
  13. }
  14. }
  15. return array_filter($dir_names);
  16. }
  17.  
  18. return [];
  19. }
  20. try{
  21. $multi_dir_path = "dir_101";
  22. if(is_dir($multi_dir_path)){
  23. // Open ZipArchive
  24. $zip = new ZipArchive();
  25. // Create Compressed file if Exists, otherwise Overwrite
  26. if($zip->open('sample_compressed.zip', ZipArchive::OVERWRITE|ZipArchive::CREATE) !== TRUE){
  27. die("An error occurred while creating your zip file");
  28. }
  29. $zip->addGlob("{$multi_dir_path}/*.*", 0, [ "add_to_path" => "{$multi_dir_path}/" ]);
  30. /**
  31.   * List All directories inside the selected path
  32.   */
  33. $scannedDir = scandir($multi_dir_path);
  34. foreach($scannedDir as $name){
  35. if(!in_array($name, ['.', '..']) && is_dir($multi_dir_path."/".$name)){
  36. $dir_names[] = $multi_dir_path."/".$name;
  37. $dir_names = array_merge($dir_names, get_directories($multi_dir_path."/".$name));
  38. }
  39. }
  40. // Adding directories files into the archive
  41. if(!empty($dir_names)){
  42. foreach($dir_names as $dir){
  43. $zip->addGlob("{$dir}/*.*", 0, [ "add_to_path" => "{$dir}/" ]);
  44. }
  45. }
  46.  
  47. $zip->close();
  48. echo "Zip file has been created successfully.";
  49. }else{
  50. echo "Selected Directory does not exists.";
  51. }
  52.  
  53. }catch(Exception $e){
  54. echo "Creating the compressed file failed.\n";
  55. print_r($e->getMessage());
  56. }
  57.  
  58. ?>

Creating a Zip file with files, folder, and multiple child folder in PHP

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:

  1. <?php
  2. try{
  3. // Open ZipArchive
  4. $zip = new ZipArchive();
  5. // Create Compressed file if Exists, otherwise Overwrite
  6. if($zip->open('sample_compressed.zip', ZipArchive::CREATE) !== TRUE){
  7. die("An error occurred while creating your zip file");
  8. }
  9. $zip->extractTo("uncompressed");
  10.  
  11. $zip->close();
  12. echo "Zip file has been extracted successfully.";
  13. }catch(Exception $e){
  14. echo "Extracting the compressed file failed.\n";
  15. print_r($e->getMessage());
  16. }
  17.  
  18. ?>

Extracting the compressed file in PHP

Here's the following snippet that demonstrates the usage of uncompressing only the selected files and folders of a compressed file:

  1. <?php
  2. try{
  3. // Open ZipArchive
  4. $zip = new ZipArchive();
  5. // Create Compressed file if Exists, otherwise Overwrite
  6. if($zip->open('sample_compressed.zip', ZipArchive::CREATE) !== TRUE){
  7. die("An error occurred while creating your zip file");
  8. }
  9. $zip->extractTo("uncompressed", ["dir_101/file_101.txt", "file_102.txt"]);
  10.  
  11. $zip->close();
  12. echo "Zip file has been extracted successfully.";
  13. }catch(Exception $e){
  14. echo "Extracting the compressed file failed.\n";
  15. print_r($e->getMessage());
  16. }
  17.  
  18. ?>

Extracting the selected files and folders of a compressed file in PHP

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