user login by php code
Could you use a rest endpoint? Because this is already handled by drupal core. See for example this or this
Otherwise I think you're just missing user_login_finalize after your check if the user is logged in.
user_login_finalize($user);
//Eventually redirect the user somewhere
$user_destination = \Drupal::destination()-&gt;get();
$response = new RedirectResponse($user_destination);
$response-&gt;send();