Accessing Drupal resources using an external file

I created an external PHP file and I wan’t to access all of my Drupal resources within that file. The path for the file might be like this:

  1. http://mydrupal.com/myfile.php, OR
  2. http://mydrupal.com/myfolder/myfile.php

Basically the file must be within Drupal’s directory. If outside, than it’s better to go with Drupal’s Services module.

There are two versions of the source code, Drupal-6 and Drupal-7. Also, there is a small code-change if you deploy the file in Windows environment.

Here are the PHP codes:

//Drupal-7 version
global $base_url; //before DRUPAL BOOTSTRAP
$base_url = (array_key_exists('HTTPS', $_SERVER) ? 'https://' : 'http://').$_SERVER['HTTP_HOST'];

$path = '';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

define('DRUPAL_ROOT',$path);
include_once 'includes/bootstrap.inc';

drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

global $user;
print_r($user);
//Drupal-6 version
chdir("<DRUPAL-ROOT-PATH>");

global $base_url; //before DRUPAL BOOTSTRAP
$base_url = (array_key_exists('HTTPS', $_SERVER) ? 'https://' : 'http://').$_SERVER['HTTP_HOST'];

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

global $user;
print_r($user);

Try login in your Drupal, then execute the file. If success, you should see the object variable of the current user, if not, you might see the anonymous user object.

Windows users need to tweak the code a bit, because usually we use http://localhost/etcetc for the URL which will make variable $_SERVER[‘HTTP_HOST’] same for every URLs. That’s why you need to add something like this:

...
$base_url = (array_key_exists('HTTPS', $_SERVER) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . '/<SUBFOLDER>';
...

<SUBFOLDER> is your folder where the file resides.

Leave a comment