首页 > 解决方案 > 来自 PHP 文件的 Drupal 8 服务调用

问题描述

我想在外部 php 文件中运行 Drupal 8 的代码。请指导我实现这一目标。

$user = \Drupal::currentUser();
\Drupal::service('session_manager')->destroy();
$user->setAccount(new AnonymousUserSession());

标签: drupaldrupal-8

解决方案


当您直接访问此页面时,它将注销活动用户。如果没有活动会话,它什么也不做,只是显示一个空白页面。

坦率地说,除非您必须使用这种方法,否则如果您详细解释您的目标,可能会有更好的“Drupal 方式”解决方案。

否则,此脚本有效:

<?php

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

// Change the directory to the Drupal root.
chdir('..');

$autoloader = require_once 'autoload.php';

$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->prepareLegacyRequest($request);

\Drupal::moduleHandler()->addModule('user', 'core/modules/user');
\Drupal::moduleHandler()->load('user');

$account = \Drupal::service('authentication')->authenticate($request);
if ($account) {
  \Drupal::currentUser()->setAccount($account);
  user_logout();
}

推荐阅读