Create backups from a custom module

Last updated on
22 January 2021

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

Making backups via Backup and Migrate

This guide explains how you can make backups in your own module via Backup and Migrate.

Steps in preparation:

Make a new destination

  • Go to admin/config/system/backup_migrate/destination and "Create a new Destination", I choose "Server Directory"
  • Give it a name e.g. backups_from_my_own_module
  • Give it a Directory path e.g. private://backups_from_my_own_module
  • Save destination
  • Back in the Destinations overview, click on edit next to your new destination
  • Notice the number in the url, it's something like this: admin/config/system/backup_migrate/destination/list/edit/02658b44d3e41ad8c70d500ed30b8fc7
  • 02658b44d3e41ad8c70d500ed30b8fc7 is the destination_id, you'll need this for later

Make a new profile

  • Go to admin/config/system/backup_migrate/profile and "Add Profile"
  • Fill in the form (I prefer Timestamp format Y-m-d-H-i-s)
  • Save profile
  • Back in the Profiles overview, click on edit next to your new profile
  • Notice the number in the url, it's something like this: admin/config/system/backup_migrate/profile/list/edit/21e5efd20f359908d3681ceff52b6f00
  • 21e5efd20f359908d3681ceff52b6f00 is the profile_id, you'll need this for later

In your module file

You need to include two files to make this work; destinations.inc and profiles.inc

The main backup function need a $settings array. Get the array by running backup_migrate_get_profile($profile_id). Then you need to add the destination_id manually to this array, the run backup_migrate_perform_backup($settings) to make the backup.

The code may look something like this:

module_load_include('inc', 'backup_migrate', 'includes/destinations');
module_load_include('inc', 'backup_migrate', 'includes/profiles');

$profile_id = '21e5efd20f359908d3681ceff52b6f00';
$destination_id = '02658b44d3e41ad8c70d500ed30b8fc7';

$settings = backup_migrate_get_profile($profile_id);
$settings->destination_id = $destination_id;

backup_migrate_perform_backup($settings);

Store config in settings.php

Instead of hardcoding the profile_id and destination_id in the module, you could configure them in settings.php like this:

$conf['backup_profile_id'] = 'xxx';
$conf['backup_destination_id'] = 'xxx';

and then get them in your module like this:

$profile_id = variable_get('backup_profile_id', 'missing');
$destination_id = variable_get('backup_destination_id', 'missing');

Check the variables for 'missing' and display an error, halt the process accordingly.

Help improve this page

Page status: No known problems

You can: