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
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__);
// 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.
$user = user_load(1);
This script can now be execute from the command line, like "php [path to script]"