print username in custom php drupal bootstrap full

Created on 27 September 2024, 3 months ago

Hi, first sorry for my bad english...
I'm neewbie in drupal 10
I have a custom php page in subdirectory of drupal root, I would like to print on the current user page that is visiting it, "welcome User Foo" I searched online for a solution to make drupal_bootstrap_full like in drupal 7.
This is the code found:

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

// Change the directory to the Drupal root.
chdir('G:\apache8\htdocs');
$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'));
  }
  

}

catch (HttpExceptionInterface $e) {
  $response = new Response('', $e->getStatusCode());
  $response->prepare($request)->send();
  exit;
}



$current_user = \Drupal::currentUser();

$uid = $current_user->id();
//It returns user id of current user.

$user_mail = $current_user->getEmail();
//It returns user email id.

$user_display_name = $current_user->getDisplayName();
//It returns user display name.

$user_account_name = $current_user->getAccountName();
//It returns user account name.

$user_roles = $current_user->getRoles();
//It returns array of current user has.

$current_user->isAnonymous();
//It returns true or false.

$current_user->isAuthenticated();
//It returns true or false.

$current_user->getLastAccessedTime();
//It returns timestamp of last logged in time for this user

the page does not declare errors but when I add the print $user
print $current_user;
the page crashes with the writing "The website encountered an unexpected error. Try again later."
there are no errors in the developer console.
I hope you can help me, thanks in advance, Luca

💬 Support request
Status

Active

Version

10.3

Component

bootstrap system

Created by

🇮🇹Italy linno

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @linno
  • The Drupal Core issue queue isn't an ideal place for general programming questions. I recommend looking into better support options . In particular, the #support channel in Slack is a good starting place.

    Some tips:

    • Bootstrapping Drupal in separate files is an advanced and somewhat unusual coding style that requires deep knowledge. Writing Drupal modules is the ordinary way.
    • 500 errors are normally logged by PHP. You have to consult the log or adjust PHP's error_reporting value to debug PHP code.
Production build 0.71.5 2024