Use the following code for programmatically login a user in drupal 7



//Auto login new user
$account = user_load($uid);// $uid is the user id
$user_account = array('uid' => $account->uid);
user_login_submit(array(), $user_account);
Use the following code for programmatically logging in a user in drupal 8.

$user = \Drupal\user\Entity\User::load($uid); // $uid is the user id
user_login_finalize($user);