How to Send the Whole Database Back-up through email by Cron Jobs in Codeigniter

Some projects need database backup every day, and manual database backup may not possible regularly. That's why we need some techniques by which we can create database backup automatically. In the Codeigniter framework, you can send the whole database back-up through email at the scheduled time by setting cron jobs.

It's a very easy process. First load the database utility class $this->load->dbutil() and use $this->dbutil->backup() to create the back-up file, and save the file in a directory of your project (here I used 'downloads' directory in the root directory), then send an email with attached the database file.

To save the memory space of the server, you can unlink the database file every time after sending the email.

public function index()
        {  
            $this->load->dbutil();          
              $file_array = array(     
                'format'      => 'zip',             
                'filename'    => 'database_name.sql'
                );
            $backup =& $this->dbutil->backup($file_array); 
            $db_name = 'backup-on-'. date("Y-m-d-H-i-s") .'.zip';
            $save = 'downloads/'.$db_name;            
            $this->load->helper('file');
            write_file($save, $backup); 
            
           ######Email Sending Start######
                             $this->load->library('email');				
			     $config['wordwrap'] = TRUE;
			     $config['validate'] = TRUE;
                             //Important section
			     $config['mailtype'] = 'html';
			     $this->email->initialize($config);										
			     $this->email->from('no-reply@xyz.com');
                             //Important section
			     $this->email->to('abcd@xyz.com'); 
			     $this->email->subject('Your Mail Subject');
                             //Important section
			     $this->email->message('Please download the zip file below');
                             $this->email->attach(site_url().'/'.$save);
                             //Important section
			     $this->email->send();                                        
           ######Email Sending End######                                        
           unlink($save);                                 
        }

Conclusion:

This is very important part in Codeigniter framework. The above code is developed and tested by me. Please share your review in the comment section. See you on my next blog.

Comments

We Serve clients globally in diverse industries

Stay Upto Date With Our Newsletter.