Codeigniter Create Zip File and Download Example

By Hardik Savani November 5, 2023 Category : PHP Codeigniter

Sometime, we may require to create and download zip file in codeigniter 3 project. In this tutorial, i will show you how to create zip file in codeigniter using zip library.

Whenever, we have lot's of files and need to give download to user when click on submit button, at that we never give one by one file to download because it is small size of files might be and it take time to download one by one. But if you create zip file and put all the files on zip then it can be very fast download and user don't need to wait so much time. So, in this example i will let you know how you can create zip file with download in codeigniter application.

Here, we will just create one route for download zip file with one "ZipController". i write creating zip file code and download code on index(). So just follow this two things.

Create Route:

In this step we need to add one route for download zip file after creating. so open routes.php file and add code like as bellow:

application/config/routes.php

$route['create-zip'] = "ZipController";

Create Controller:

Here, we need to create ZipController with index() method. I write creating zip file code and download code on index(). Let's just create it.

application/controllers/ZipController.php

<?php

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

class ZipController extends CI_Controller {

/**

* Get All Data from this method.

*

* @return Response

*/

public function __construct() {

parent::__construct();

$this->load->library('zip');

}

/**

* Get All Data from this method.

*

* @return Response

*/

public function index()

{

$fileName = 'itsolutionstuff.txt';

$fileData = 'This file created by Itsolutionstuff.com';

$this->zip->add_data($fileName, $fileData);

$fileName2 = 'itsolutionstuff_file2.txt';

$fileData2 = 'This file created by Itsolutionstuff.com - 2';

$this->zip->add_data($fileName2, $fileData2);

$this->zip->download('Itsolutionstuff_zip.zip');

}

}

Now you can run and see how it works.

I hope it can help you...

Shares