How to log in programmatically as user 1 in Drupal 7

| | 1 min read

Once in a while you will come across a Drupal site where you have to login to the site without having access to the credentials of user 1. You can easily reset the password of user 1 directly in the database or you can create a small work around to login to the site. Here is how you can login to the Drupal 7 site programmatically as user 1 without knowing user 1 credentials.

In Drupal 7 you can do this by copying over index.php as test.php (or whatever name you wish to call it) and replace the last line

menu_execute_active_handler();

with

global $user;
$user = user_load(1);
drupal_session_regenerate();
drupal_goto('user');

Remember to delete this file immediately after logging in as it would be a gargantuan security vulnerability to leave this file in the website as anybody who accesses this file will be able to gain access to your site as user 1.