Web design, programming, graphics, and pretty much anything else I care about.

Bootstrapping Drupal from an external sript

There are occasions where connecting to Drupal from an external script comes in handy. Connecting from a non-Drupal system, performing simple maintenance tasks, or just quick and dirty one time operations where you don't feel like making a module. I do this often when creating import scripts to bring data into a new site.

// Set the working directory to your Drupal root

// For Drupal 6

// For Drupal 7
define('DRUPAL_ROOT', '/path/to/drupal');
DRUPAL_ROOT . '/includes/bootstrap.inc';

// Load Drupal
// If you are not running the script through a web server, it may be necessary to set server variables yourself. It is also important to set HTTP_HOST if you are using multi-site.
$_SERVER['HTTP_HOST'] = 'www.example.com:8888';
$_SERVER['SCRIPT_NAME'] = '/' . basename(__FILE__);
// You don't have to do a full bootstrap. Check the API for all the different phases you can use.

// Drupal is now fully bootstrapped. You have full access to the API.
// ...add your code here.

// By default you will be seen as anonymous, so it is handy to change to user 1 or whatever user you require.
global $user;
$user = user_load(1);

This script can now be execute from the command line, like "php [path to script]"