Creating and downloading ZIP files

You may wish to generate ZIP folders from your application and force a download for your users; for example, if you have a group of files, such as a press pack, which you wish to be kept together, or a set of CSV files. Saving them into a ZIP file and allowing a download is a great way to do this.

How to do it...

We're going to create a new file:

  • /path/to/codeigniter/application/controllers/zip.php

And copy the following code into it:

<?php if (!defined('BASEPATH')) exit('No direct script access allowed'), 
class Zip extends CI_Controller { 
  function __construct() { 
    parent::__construct(); 
    $this->load->helper('form'), 
    $this->load->helper('url'), 
    $this->load->library('zip'), 
  } 

  public function index() { 
    redirect('zip/zipme'), 
  } 

  public function zipme() {        

  $file_name = '/path/to/zip/tozip.txt'; 

  // Create some data for the file 
  $data = 'This is a string of text which we will use to write to the file in the variable $file_name'; 

  // Set the time (to be used as ZIP filename) 
  $date = date("d-m-Y", time()); 

  // Save some data to the ZIP archive 
  $this->zip->add_data($file_name, $data); 

  // Create the ZIP archive on your server - make sure this path is 
  // outside of your web root 
  $this->zip->archive('/path/in/zip/'.$date.'.zip'), 

  // Download the ZIP archive 
  $this->zip->download($date.'.zip'), 

  // Clear the cached ZIP archive 
  $this->zip->clear_data(); 
  } 
} 

How it works...

This is actually quite simple, we start by declaring a $file_name. This is a string, you'll notice that the filename also contains a folder name my_zipped_files_folder—you don't have to include a folder but if you do CodeIgniter will automatically create a folder in the ZIP archive.

We then create some data—in this case it is written as a string of text; however, it could easily be output from a database. For example, we could change the $data line to:

$data = ''; 

foreach ($database_result->result() as $row) { 
  $data .= $row->item_1; 
  $data .= $row->item_2; 
  $data .= $row->item_3; 
} 

After we create our $data we then create the date, which we'll use in the filename for our ZIP. The line $this->zip->add_data($file_name, $data); takes as argument the filename and data we created earlier and creates a file inside the ZIP file and fills it with the string in $data. $this->zip->archive('/path/to/your/zip/folder/'.$date.'.zip'), will write the ZIP to the disc using $date as the ZIP filename. $this->zip->download($date.'.zip'), forces the ZIP file to open in the client browser and $this->zip->clear_data(); will clear the ZIP file from the cache.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.168.172