You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在外部PHP文件中运行Drupal 8的指定代码?

How to Run Drupal 8 User Logout Logic in an External PHP File

Got it, let's walk through exactly how to get that logout code running in an external PHP file. The key here is first bootstrapping the Drupal environment so your external file can access core services like session_manager and user classes. Here's a step-by-step breakdown:

1. Create Your External PHP File

First, make a new file (let's call it custom_logout.php) — I recommend placing it in a subdirectory like sites/default/custom/scripts/ to keep it organized and secure (avoid putting it directly in your web root where it could be accidentally accessed).

2. Bootstrap the Drupal Environment

Your external file doesn't know about Drupal's core by default, so you need to load the autoloader and bootstrap the system. Add this at the top of your file:

// Adjust this path to point to your Drupal root directory
$drupal_root = dirname(dirname(dirname(__DIR__))); // Example path if your file is in sites/default/custom/scripts/
chdir($drupal_root);

// Load Drupal's autoloader and bootstrap the full system
require_once './autoload.php';
\Drupal::bootstrap(\Drupal::BOOTSTRAP_FULL);

Note: Tweak the $drupal_root path based on where you placed your file. If it's directly in the Drupal root, just use $drupal_root = __DIR__;.

3. Add Your Logout Code (With Namespace Fix)

Your original code needs one small adjustment: the AnonymousUserSession class requires a namespace import. Add this and your logout logic below the bootstrap code:

use Drupal\Core\Session\AnonymousUserSession;

// Your logout logic, now working with Drupal's loaded environment
$user = \Drupal::currentUser();
\Drupal::service('session_manager')->destroy();
$user->setAccount(new AnonymousUserSession());

// Optional: Clear the session cookie to fully log the user out in the browser
if (isset($_COOKIE[session_name()])) {
    setcookie(session_name(), '', time() - 42000, '/');
}

4. Important Security & Usage Notes

  • File Permissions: Make sure the file has proper permissions (not world-writable) to prevent unauthorized access.
  • Access Control: Don't expose this file publicly. Run it via the command line (php sites/default/custom/scripts/custom_logout.php) or trigger it through a secure, authenticated route if you need to run it via a browser.
  • Drupal Version Compatibility: This approach works for Drupal 8, 9, and 10 since the core session/user APIs here haven't changed much.

That's it! When you run this file, it'll properly destroy the user's session and switch their account to an anonymous one, just like your original code intended.

内容的提问来源于stack exchange,提问作者pravat231

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:23:37