Create a page outside of the CMS workflow that has access to Drupal’s built-in functions.
There are scenarios, the deeper you get into Drupal, where you will need to access Drupal’s database and functions, but outside of the scope of the CMS. For instance, you may need to create an AJAX callback that hooks into the database for a TinyMCE plugin, or you may be looking for ways to port over a custom CMS to Drupal… These are just a couple of reasons for having an easy way to hook into Drupal at the base level. And like with everything Drupal, there is a Drupal function for this: drupal_bootstrap($phase = NULL, $new_phase = TRUE) Before we show how to use this function in code, let’s break it down a little.
Phase is a predefined constant that identifies which phase of Drupal to load. As the docs state “each phase adds to the previous one, so invoking a later phase automatically runs the earlier phases as well.” The constants available for the $phase variable (in order) are:
Sets up the script environment and loads settings.php
Attempts to serve a page from the cache
Initializes the database system and registers autoload functions
Loads system variables and all enabled bootstrap modules
Initialize session handling
Invokes hook_boot(), initializes locking system, and sends HTTP headers
Finds the language of the page
Drupal is fully loaded; validate and fix input data.
Remember, calling any of the phases automatically will load any preceding phases as well.
TRUE declares that drupal_boostrap() will run recursively, loading all previous phases up to the one we have chosen.
Now that we have the basics of the function out of the way, let’s see how we can implement it. Create a custom page called test.php and insert the code below:
// Get path of drupal install. $drupal_path = $_SERVER['DOCUMENT_ROOT']; // Create a constant DRUPAL_ROOT that // defines our path to the drupal install define('DRUPAL_ROOT', $drupal_path); // We need to load the bootstrap.inc file so we can // have access to the drupal_bootsrap() function require_once DRUPAL_ROOT . '/includes/bootstrap.inc'; // Bootstrap Drupal at the phase that you need drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); // Our custom page now has access to Drupal functions // such as node_load() and db_query() $node = node_load(1);
(As a side note, if all you need is to query the database, then setting your phase to DRUPAL_BOOTSTRAP_DATABASE will be much less costly in terms of load time).
That is basically all you need to tie Drupal into any custom page!