How to upload and Extract Zip file in CodeIgniter

In CodeIgniter, there is a zip library for creating a zip file but there is no library available for extracting the zip file.

To extract need to use ZipArchive Class.

Load the file and extract it to a location using the ZipArchive Class object.

In this tutorial, I show how you can upload and extract a zip file to a specific location in CodeIgniter.

How to upload and Extract Zip file in CodeIgniter


Contents

  1. Create directories
  2. Configuration
  3. Controller
  4. View
  5. Conclusion

1. Create directories

Create two directories at project root –

  • uploads – To store uploaded zip files.
  • files – To extract the uploaded zip file.

How to upload and extract Zip file in CodeIgniter


2. Configuration

Default controller

Open application/config/routes.php and edit default_controller value to Unzip.

$route['default_controller'] = 'Unzip';

3. Controller

Create a Unzip.php file in application/controllers/ directory.

Created 3 methods –

  • __construct – Load url helper and session library. I loaded session library only to display the message on view file using flashdata.
  • index – Load index_view view file.
  • extract – This method is call on <form >. submit. From here, upload and extract the file.

Check file selected or not. If selected then set the upload preference and load upload library.

Extract file

If file uploaded successfully then create an object of ZipArchive Class.

Pass zip file path in $zip->open().

If its return TRUE then assign the extract location ("files/") in $extractpath.

Call $zip->extractTo() to extract the file. Pass the $extractpath in the method.

Completed Code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Unzip extends CI_Controller {

   public function __construct(){

     parent::__construct();
     $this->load->helper('url');

     // Load session library 
     $this->load->library('session');

  }

  public function index(){
     // Load view
     $this->load->view('index_view');
  }

  // Upload and Extract zip file
  public function extract(){

     // Check form submit or not 
     if($this->input->post('submit') != NULL ){ 

       if(!empty($_FILES['file']['name'])){ 
          // Set preference 
          $config['upload_path'] = 'uploads/'; 
          $config['allowed_types'] = 'zip'; 
          $config['max_size'] = '5120'; // max_size in kb (5 MB) 
          $config['file_name'] = $_FILES['file']['name'];

          // Load upload library 
          $this->load->library('upload',$config); 

          // File upload
          if($this->upload->do_upload('file')){ 
             // Get data about the file
             $uploadData = $this->upload->data(); 
             $filename = $uploadData['file_name'];

             ## Extract the zip file ---- start
             $zip = new ZipArchive;
             $res = $zip->open("uploads/".$filename);
             if ($res === TRUE) {

               // Unzip path
               $extractpath = "files/";

               // Extract file
               $zip->extractTo($extractpath);
               $zip->close();

               $this->session->set_flashdata('msg','Upload & Extract successfully.');
             } else {
               $this->session->set_flashdata('msg','Failed to extract.');
             }
             ## ---- end

         }else{ 
            $this->session->set_flashdata('msg','Failed to upload');
         } 
      }else{ 
         $this->session->set_flashdata('msg','Failed to upload');
      } 

     }
     redirect('/');
  }

}

4. View

Create a index_view.php file application/views/ directory.

Create a <form >. Set its action='<?= base_url() ?>index.php/unzip/extract/‘.

Within the <form> add file element and a submit button.

Completed Code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>How to upload and Extract Zip file in CodeIgniter</title>
  </head>
  <body>

    <?php 
    // Message
    echo $this->session->flashdata('msg');
    ?>
    <!-- Form -->
    <form method='post' action='<?= base_url() ?>index.php/unzip/extract/' enctype='multipart/form-data'>
      <input type='file' name='file'>
      <input type="submit" name="submit" value="Upload & Extract">
    </form>

  </body>
</html>

5. Conclusion

You can remove the upload file code if you want to load and extract the existing zip file stored in the server.

Pass the file path in $zip->open() and update the extract location.

If you found this tutorial helpful then don't forget to share.

Leave a Comment