Using Drupal data, functions, and session variables in an external PHP script
Tue, 12/13/2011 - 19:44 — Charlie
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.
Tags:

Comments
Thanks!
You saved my life today. Essential knowledge right here.
Session still not persistent
Hi there,
i tried your code, and if i add " echo session_id(); " at the end it shows me the drupal session_id (sometimes with underscores, so i know it's not the native php session). However the session_id changes with each page reload, and i lose the $_SESSION data as well. This code will always show 'not set ...':
echo session_id().'<br/>';
if(!isset($_SESSION['test']))
{
$_SESSION['test'] = time();
echo 'not set...';
}
else
{
echo $_SESSION['test'];
}
print_r($_SESSION);
Do you have any idea what my issue is? i use Drupal7, don't get any inline error messages, no records in drupals 'session' table and see nothing in my php error logs.
cheers, Daniel
( SELECT reverse('moc.etagniw@leinad') as email; )
My first guess would be
My first guess would be caching - do you have it enabled for anonymous visitors?
Try adding this block of code before your echo $_SESSION stuff:
global $user;if ($user->uid == 0) {
drupal_session_start();
}
thanks
Seriously, Thank you so much!
Thanks
A timely piece of info. Thanks
Add new comment