Drupal - Programmatically User login not working

your code is Ok.

just add the following namespace:

use Drupal\user\Entity\User;
use Symfony\Component\HttpFoundation\RedirectResponse;

delete in your code:

 user_login_finalize($user);

and

 exit(0);

A complete example would be.

use Drupal\user\Entity\User;
use Symfony\Component\HttpFoundation\RedirectResponse;

$uid=1;

if(isset($uid)) {
  $user = User::load($uid);
  user_login_finalize($user);
  $user_destination = \Drupal::destination()->get();
  $response = new RedirectResponse($user_destination);
  $response->send();
ksm($user);
}

if you have installed the

devel

module and the

Kint

submodule, You can use the function

ksm()

, to show the information of a variable.

Tags:

Users

8