How do I log in a user? I want to log in Drupal 8 users from an external PHP file. I am trying the following code.
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
use Drupal\user\UserInterface;
//$autoloader = include('/vendor/autoload.php');
$autoloader = require_once __DIR__ . '/vendor/autoload.php'; 
$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel-&gt;handle($request);

// ID of the user.
// REPLACE WITH WHATEVER ID YOU WANT TO LOGIN AS;
$uid = 100; 
$user = Drupal\user\Entity\User::load($uid);

// This is required to call user_login_finalize here.
$kernel-&gt;prepareLegacyRequest($request);
user_login_finalize($user);

$response-&gt;send();

$kernel-&gt;terminate($request, $response);

When I run it, I get the following error.

TypeError: Argument 1 passed to user_login_finalize() must implement interface Drupal\user\UserInterface, null given, called in /var/www/html/stocksee/public_html/component/login.php on line 22 in user_login_finalize() (line 554 of core/modules/user/user.module).

Please help me.
I'd say in this specific case the error message looks like saying that $user is NULL. You need to validate that User::load returns a valid UserInterface because if the $uid passed to the method is not found, it will return NULL, which is the value you are getting. Try with a valid uid like 1, see what happens and move ahead from there.