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.

Comments

Tyler's picture

You saved my life today. Essential knowledge right here.

Daniel's picture

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; )

Charlie's picture

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();
}

ramZ's picture

Seriously, Thank you so much!

Trevor's picture

A timely piece of info. Thanks

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.