How to get the current user? External App

Hi there,

some time ago we wrote a little helping app, which worked fine.

After upgrading from NC 18 > 19, we got an issue with the current logged in user.

Working solution:

  • including the base.php (require_once(’…/lib/base.php’);).

  • getting the current user with admin privileges ($getusername = OCP\User::getUser();).

  • checked the user/group db and allowed the access.

Problem now:

  • including the base.php now crashes the app (unlimited loading)

Question:

What’s the easiest way to simple get the current user name (display name) in PHP?

Sry for the (simple) question, but we stuck at the moment.

Thx, with best regards

Maybe
<?php echo get_current_user(); ?>

Thx for the reply.
This is the server/php user.
We need the current nextcloud user, which we formaly got with: OCP\User::getUser();.

You can use the userSession from dependency Injection.
This gives you an Instance of IUser, of which you can use getDisplayName()
$userSession->getUser()->getDisplayName()

See e.g.

1 Like

I know this thread is a bit dated already, but I found another solution that may be helpful for others too:

If your external app or website resides inside your nextcloud domain and you use SSL (which you should!), you can just check $_SERVER[‘HTTP_COOKIE’] for the string “nc_username=”. The current user name just starts after that. The string will only be present while the user is logged in into nextcloud.
To prevent sending out any data while the user is not being logged in, you may use something like this:

<?php $pos = strpos($_SERVER['HTTP_COOKIE'], 'nc_username='); if ($pos === false) { die; } ?>
1 Like