Database backup using Codeigniter Database Utility Class

Database backup using Codeigniter Database Utility Class

In this post, I will show how to take database backup using codeigniter database utility class. Database backup is the most important required thing of web application to prevent data lost if data lost by any reason. You can easily take backup of database using codeigniter dbutil class.

1.Create a view called backup.php.


<title>Database Backup Using Codeigniter</title>
font-family: Verdana;
font-size: 18pt;
font-style: normal;
font-weight: bold;
text-align: center;

font-family: Verdana;
font-size: 12pt;
font-style: normal;
font-weight: bold;
border-collapse: collapse;
font-size: 11px;
<h3>Database Backup Using Codeigniter</h3>
<?php echo form_open('backup/database',array('name' => 'backup')); ?>
<table align="center" cellpadding = "5">
<td colspan="5" align="center">
<input type="submit" name="backup" value="Take Backup"/></td>
<?php echo form_close();?>

2. Next, create a controller to put all database backup functionality.Here is how the database backup code looks.


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

class BackupController extends CI_Controller {
public function __construct()
public function index(){
function database_backup()
$prefs = array('format' => 'zip', 'filename' => 'Database-backup_' . date('Y-m-d_H-i'));
$backup = $this->dbutil->backup($prefs);
if (!write_file('./uploads/backup/BD-backup_' . date('Y-m-d_H-i') . '.zip', $backup)) {
echo "Error while creating auto database backup!";
else {
echo "Database backup has been successfully Created";

Change the routes as showing below.

$route['backup'] = 'backupcontroller';
$route['backup/database'] = 'backupcontroller/database_backup';

Additionally, If you want to take backup of another database that is not using by the codeigniter app but that has in same server then you can write code below showing to take backup of another database.

First, Add another database at the bottom of database.php file

$db['another_db_name'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'another_db_name',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE

Next, load the another database before taking backup of another database.Find below the code.

$this->db = $this->load->database('another_db_name', TRUE);

Note: Due to the limited execution time and memory available to PHP, very large database backup may not be possible using dbutil class.

Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion and problems if you face – let us know. We’d love to help!