Using Drupal data, functions, and session variables in an external PHP script
Just a quick post to save anyone else that runs into this. If you've created something like ajax.php to handle some minor requests outside of your primary Drupal install but you need access to things like the $user object or the PHP $_SESSION variables, you can simply bootstrap Drupal at the top of ajax.php as you need:
<?php define('DRUPAL_ROOT', $_SERVER['DOCUMENT_ROOT']); $base_url = 'http://'.$_SERVER['HTTP_HOST']; require_once DRUPAL_ROOT . '/includes/bootstrap.inc'; drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION); ?>
This is really quite simple. We're definine the path to "DRUPAL_ROOT" which is used throughout bootstrap.inc. Then we're defining the $base_url which will be used by Drupal to make sure we're on the same domain. Finally, we load bootstrap.inc and run drupal_bootstrap() to whatever level we need. Some options are:
- DRUPAL_BOOTSTRAP_FULL will give you everything; the $user object, $_SESSION variables, you could even run
print drupal_render(node_view(node_load(123))) to print out a rendered node.
- DRUPAL_BOOTSTRAP_DATABASE will give you full access to the database abstraction layer.
- DRUPAL_BOOTSTRAP_SESSION will allow your PHP $_SESSION variables to use Drupal's session handler, thus passing variables between the two.