How to unzip or extract zip files in PHP?

By Faruque Ahamed Mollick

Today in this post, I am going to show you how to extract zip files in a specific directory path in PHP with the example code.

PHP already has built-in class ZipArchive. To extract a .zip file and moving the contents we first need to create the object of ZipArchive. After that, we can open the zip file through PHP and extract it to a specific path.

Below is a simple given code which will extract our zip file to a specific directory for example “directory/mydir”.

below is the simple code which will do this job:

<?php
  $zip_obj = new ZipArchive;
  $zip_obj->open('sample.zip');
  $zip_obj->extractTo('directory/mydir');
?>

The above code will simply open the sample.zip file and extract content from it and then move it to the directory that we have specified.

Get country data on clicking on map – PHP source code



Search for restaurants using Zomato API in PHP

But what happened if the zip file does not exist. It will display some kind of warning which has no readability value. To overcome this problem and show your custom message when the zip file does not exist, below is the modified PHP code:

<?php
  $zip_obj = new ZipArchive;

  if ($zip_obj->open('sample.zip') === TRUE) {
       $zip_obj->extractTo('Main-directory/mydir');
       echo "Zip exists and successfully moved";
  }
  else {
  	   echo "The zip file does not exist";
  }
?>

The above code will first check if the zip file exists or not and if exist, it will extract the zip file and move content to the directory. With this way, we succeed in avoiding the PHP warning message and finally increase the readability for non-developers.

Well, you don’t have to worry if the directory does not exist. Here we have moved the zip extracted content to a directory. But what happened if the directory path we specified does not exist?

Protect website from SQL Injection in PHP

Difference between PHP include and require statements

Well, PHP will create the directory automatically before move the extracted content and then keep the content inside that directory. So we don’t need to worry about that thing which is really a great advantage. this is another magic of PHP.

So extracting a .zip file and moving the extracted content in a specific directory is really is an easy task. There is nothing complicated in doing this task.

I hope you enjoyed this interesting tutorial post.

One response to “How to unzip or extract zip files in PHP?”

  1. Gulshan Kumar says:

    Wow!! That’s amazing. I generally do ZIP/UNZIP using SSH.

Leave a Reply

Your email address will not be published. Required fields are marked *