Bootstrap drupal from outside of the drupal root

I forgot where I found this, but I was getting annoyed at my inability to bootstrap drupal without placing a file in the Drupal root, so, in the interests of sharing, here it is. If I remember the source of this code anytime soon, I will, of course, mention it. For those unfamiliar with this procedure, insert this code at the beginning of your drupal php scripts, change script.php and mysite.example.com to appropriate values, and you can you use the full glory of the Drupal API in your script and stick it wherever you like in your file structure. This is great for multiple sites sharing the same codebase. That said, be careful not to accidentally change other sites hosted on your codebase using this approach, the potential is there, because in order to bootstrap drupal we are changing to its root directory.

$_SERVER['SCRIPT_NAME'] = '/script.php';
$_SERVER['SCRIPT_FILENAME'] = '/script.php';
$_SERVER['HTTP_HOST'] = 'mysite.example.com';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$_SERVER['REQUEST_METHOD'] = 'POST';

chdir('/path/to/drupal/');
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

If you really wanna have some fun, try bootstrapping Drupal from the php command line.

Unsuccessful paths tried:

  • Using ini_set() to set the include path to include the Drupal root directory.
  • Trying to include all the files included by bootstrap.inc manually.

Update (7 nov) - I've been thinking about this procedure today, in the context of a Drupal multisite farm I use at my work, and I think it's problematic that I can do this on that install from anywhere in the file structure. The potential exists to use this code in a multisite context to change sites to which you would normally not have access. It's a standard shared hosting problem, aggravated by the way that multi-site is built into Drupal and the need to bootstrap from the root folder.

Comments

Very good post, thanks a lot.

Very good post, thanks a lot.