Restrict the site access through http password authentication

Public

When you want the site to be accessible only to certain people but still have user roles in place, use this approach. Note that this will throw errors with Drush.

Get raw version
php
  1. /**
  2.  * Implementation of hook_boot().
  3.  *
  4.  * Ask for user credentials and try to authenticate.
  5.  */
  6. function hook_boot() {
  7. require_once DRUPAL_ROOT . '/includes/password.inc';
  8.  
  9. if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
  10. $query = "SELECT pass FROM {users} WHERE name = :name";
  11. $result = db_query($query, array(':name' => $_SERVER['PHP_AUTH_USER']));
  12. $account = new stdClass();
  13. foreach ($result as $row) {
  14. $account->pass = $row->pass;
  15. }
  16. if (isset($account->pass)) {
  17. if (user_check_password($_SERVER['PHP_AUTH_PW'], $account)) {
  18. return;
  19. }
  20. }
  21. }
  22.  
  23. header('WWW-Authenticate: Basic realm="Development"');
  24. header('HTTP/1.0 401 Unauthorized');
  25. exit;
  26. }