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.

<?php
// Set the working directory to your Drupal root

// For Drupal 6
chdir('/var/www/drupal/');
require_once
'./includes/bootstrap.inc';

// For Drupal 7
define('DRUPAL_ROOT', '/path/to/drupal');
require_once
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['REMOTE_ADDR'] = '127.0.0.1';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['SCRIPT_NAME'] = '/' . basename(__FILE__);
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
// 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]"