Bootstrap Drupal 7 for automated maintenance scripts
Why you should bootstrap Drupal 7
I don't always build websites with Drupal 7, but when I do they are usually large and complex applications. And large applications are typically accompanied by command line scripts to automate maintenance tasks, such as:
- Data migration
- Data export
- Data backup
- Report creation
- Cache clearing
Yes, it is possible to build a custom Drupal module and invoke its methods with an authenticated HTTP request; but that approach requires the full web stack and is inherently bound by the web server's time limit. Instead, it is best to move Drupal maintenance tasks into separate, stand-alone PHP scripts that may be executed on the command line — manually or as scheduled cron tasks. However, each PHP script must first bootstrap Drupal 7 before it can access the Drupal 7 API.
How to bootstrap Drupal 7
Bootstrapping Drupal 7 is remarkably easy. Add this snippet of code at the top of your PHP script:
<?php // Set the absolute path to the Drupal site's document root directory define('DRUPAL_ROOT', '/var/www/public'); // Ensure the REMOTE_ADDR server variable is set $_SERVER['REMOTE_ADDR'] = '127.0.0.1'; // Load Drupal require_once DRUPAL_ROOT . '/includes/bootstrap.inc'; drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
That's it. After you include this code in your PHP script, you can use the complete Drupal 7 API to manipulate your Drupal website from your command line PHP script. Be sure you change the
DRUPAL_ROOT value so that it points to your own Drupal website's document root directory.
Luke HolmesThanks Josh. This worked for me.
Extra steps I had to take as a Acquia Dev Desktop users...
You also need to ensure the $databases array in /sites/default/settings.php is populated. By default devdesktop creates and uses a new settings.php file in the /sites// directory. The bootstrap process can't find the $databases array in here so fails.
Leave a comment