jigniter™

jQuery & CodeIgniter – Perfect combination for web application

Archive for the ‘zip’ tag

How to Backup files using CodeIgniter

without comments

If you are developing a CodeIgniter application and need to backup files, let’s say in a .zip file, then you are lucky since CodeIgniter has a Zip Encoding library.

In my case, I used this library to create file backup, most of the time. But you can use it for other interesting things, for example adding string data to a .zip file and then allow users to download that file from a web page.

In this post I’ll only show the case we need to backup a directory using CodeIgniter and save the content to a .zip file.

Originally, this code read images and Flash files from the database and then save these images (binary data) into the file system. Since that action will run periodically using a Cron job, I’d like to do a backup for the existing files before overwriting. That’s where the Zip Class comes in action to compress a directory into an archive.


function _create_backup()
{
	$this->load->library('zip');
	$path = 'media/';
	$this->zip->read_dir($path);
	$result = $this->zip->archive('my_backup.zip');
	return $result;
}

If you want the zip file to have a better name, probably you can add the current date as  a suffix, so you can know where the file was created. To do that, you can replace ‘my_backup.zip’ by:


$result = $this->zip->archive('media_backup_'.date('Ymdhs').'.zip');

That will add the current date as a suffix.

Hope this snippet helps you the next time you need to backup files. If you are interested in other usages, you can refer to the CodeIgniter’s  User Guide for more information.

Written byadmin

August 29th, 2009 at 11:30 pm

Posted inSnippets Ideas

Tagged with , , ,