You have a stand-alone application that is not a Drupal module but resides in a Drupal sub-folder. And you want Drupal to manage your users. You want to access the currently logged-in Drupal user from your application. The following function will give you the current user id, name, email and roles:
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
/**
* Get Drupal current session user details.
* Passing Drupal folder, or its relative folder such as '..'
* when it is called from a Drupal sub-folder.
* Return ['id', 'name', 'email', 'roles']
*/
function get_drupal_current_user($drupal_dir) {
// Change the directory to the Drupal root.
chdir($drupal_dir);
$drupal_root = getcwd();
if ($drupal_root === false)
return [];
$autoloader = require_once 'autoload.php';
$kernel = new DrupalKernel('prod', $autoloader);
$request = Request::createFromGlobals();
// Emulate Drupal /index.php to get the current user id
$request->server->set("SCRIPT_FILENAME", $drupal_root . "/index.php");
$request->server->set("REQUEST_URI", "/");
$request->server->set("SCRIPT_NAME", "/index.php");
$request->server->set("PHP_SELF", "/index.php");
$response = $kernel->handle($request);
$user_id = \Drupal::currentUser()->id();
$acct = \Drupal\user\Entity\User::load($user_id);
if ($acct != null) {
$user_name = $acct->getDisplayName();
$user_email = $acct->getEmail();
$user_roles = $acct->getRoles();
}
else {
$user_name = "";
$user_email = "";
$user_roles = [];
}
$kernel->terminate($request, $response);
return ['id' => $user_id, 'name' => $user_name, 'email' => $user_email, 'roles' => $user_roles];
}
It emulates Drupal 9 index.php. It has to emulates index.php otherwise Drupal will create an anonymous session. Technically, you are already inside Drupal and you can call any Drupal function from within the code above.
Comments
Post a Comment