0
votes

Is there any way to execute Drupal 8 functions from an external PHP file.

3
You might want to give us some context on why you want to do this, because generally, you wouldn't do it, you would write s drupal module instead. - 2pha

3 Answers

3
votes

You can include/call Drupal's bootstrap in your script and after that call Drupal's functions. Used that for D7, but didn't try for D8. However it should work:

https://drupal.stackexchange.com/questions/174474/bootstrap-from-external-script

And to copy code from that page:

define('DRUPAL_DIR', '/usr/share/nginx/html');
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
require_once DRUPAL_DIR . '/core/includes/database.inc';
require_once DRUPAL_DIR . '/core/includes/schema.inc';
// Specify relative path to the drupal root.
$autoloader = require_once DRUPAL_DIR . '/autoload.php';

$request = Request::createFromGlobals();

// Bootstrap drupal to different levels
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
$kernel->prepareLegacyRequest($request);

$em = $kernel->getContainer()->get('entity.manager');

$entity = $em->getStorage('node')->create(
        array(
          'type' => "article",
          'title'=> "test entity",
          'body' => "body body body",
        ));

$entity->save();
1
votes

If you have Drush, you can run "drush scr [filename]" which will execute the file as well as bootstrap Drupal. I did a blog post about this - https://www.oliverdavi.es/blog/dont-bootstrap-drupal-use-drush.

I'd only use this for simple local test scripts though to test things out before moving the code into proper functions/classes/controllers/services etc.

0
votes

You can run any php code either drupal or non-drupal using Devel and Kint module like this.[Use Devel and Kint module] like this https://i.stack.imgur.com/RUKv6.png