Drupal adatbázis és egyéb szolgáltatások használata független PHP oldalon

Bootsrap from external script in drupal 7 and drupal 8 or 9

Problémás dolog használni a Drupal szolgáltatásait, olyan oldalakon, amelyek nem a keretrendszerben töltődnek be, de azért megoldható. Ehhez az alábbiakra van szükségünk:

  • Ha nem default az aktuális PHP fájl helye, akkor először el kell menteni a jelenlegi könyvtárat, majd belépni a drupal könyvtárába:
  • Be kell includolni a Drupal indítóállományát:
  • Indítani kell a Drupal inicializáló függvényét:
  • Vissza kell állítani az elmentett könyvtárat:

A teljes kód így néz ki:


//Drupal 7 version
$fz_dir = getcwd();
chdir("/drupal/"); 
require_once ("./includes/bootstrap.inc");
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
chdir($fz_dir);
... saját kód...

Drupal 8-tól a helyzet egy kicsit megváltozott és egy kicsit másféle, de alapjaiban hasonló kódot kell írni.


//Drupal 8 version

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

// This code step up in the filesystem, and search for the root of drupal 8.
while (!@stat('autoload.php')) {
  chdir('..');
}
define('ROOT',getcwd());
$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'));
  }
  require_once ROOT . '/core/includes/database.inc';
  require_once ROOT . '/core/includes/schema.inc';
 
}catch(HTTPExceptionInterface $e){
  $response = new Response('', $e->getStatusCode());
  $response->prepare($request)->send();
  exit;
}

... own code ...