Bootstrapping Drupal

- - Drupal

There are cases when you may need to access Drupal’s database and core functions from an external php script (your custom written script), it may be that writing a module is overkill or you just need to do something only once. Whatever the reason it’s really useful to be able to easily hook into Drupal at the base level.

Bootstrapping Drupal 6

chdir('/var/www/drupal/'); //set to drupal's base path
require_once './includes/bootstrap.inc'; //include drupal's built-in script called bootstrap.inc

Bootstrapping Drupal 7

define('DRUPAL_ROOT', '/path/to/drupal');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';

Example Use Case – Hooking into Drupal

Writing a script that:

  1. Hooks into Drupal’s database and fetches some info on a particular event.
  2. Using AJAX, update the DOM based on the role of the logged in user and results from the database query.

The Solution…
First, create a script that hooks into Drupal’s. I have created mine here: (/sites/all/modules/boots/myscript.php).

chdir("../../../../");
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

Now that we’ve hooked into drupal we can access various functions and global variables. Let’s start by getting some info about the user currently logged in

global $user;
if($user->uid) {
$uid= $user->uid;
$cuser= $user->name;
$email= $user->mail;
}

With the user’s id we can fetch a list of all the events this user has registered for. Database Query below:

$result = db_query("SELECT eventid, eventdate, uid
FROM drp_custom_events WHERE created_by_id = '$uid'");
while ($node = db_fetch_object($result)) {
$eventArr[] = $node->eventid;
}

$evArr= (implode(', ', $eventArr));
echo $evArr;

The results from the query can now be displayed on the front end with the help of a jquery Ajax function. That’s it, You’ve successfully Bootstrapped Drupal!


Post Tags:
Join the Newsletter

Sign up for our personalized daily newsletter

Kodesmart

#1 GUIDE TO DRUPAL, WORDPRESS, CSS AND CUSTOM CODING | BEGINNER TO PRO

  • epicallyfun

    Amazing tutorial! Thank you!