Skip to main content

Use it for question about calling Drupal functions or methods from an external PHP script.

Calling a Drupal function or the method of a Drupal class from an external PHP script means to first bootstrap Drupal from that script. In Drupal 7, that is achieved from code similar to the following one.

define('DRUPAL_ROOT', 'the Drupal root directory');
require_once DRUPAL_ROOT . '/core/vendor/autoload.php';
require_once DRUPAL_ROOT . '/core/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

With Drupal 8, it involves Symfony, and the code is similar to the following one.

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

// Change the directory to the Drupal root.
chdir('the Drupal root directory');
$autoloader = (require_once 'autoload.php');

try {
  $request = Request::createFromGlobals();
  $kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
  $kernel->boot();
  $kernel->preHandle($request);

  // Ensure the request includes the session if appropriate.
  if (PHP_SAPI !== 'cli') {
    $request->setSession($kernel->getContainer()->get('session'));
  }
} catch (HttpExceptionInterface $e) {
  $response = new Response('', $e->getStatusCode());
  $response->prepare($request)->send();
  exit;
}