Temporary Securing Drupal through Basic Auth in settings.php

We needed to protect our production site from prying eyes for a while with a basic authentication. Using apache basic auth settings seemed not enough. Or actually was too much. We wanted the theme to blend in. So these files were not supposed to get protected. Only our Drupal pages should.

The solution came from http://php.net/manual/en/features.http-auth.php. Adding the following to sites/default/settings.php makes the customer happy and drush too.

$username = 'user';
$password = 'pass';

// Make sure drush keeps working. Taken from function drush_verify_cli() but modified.
// The last part failed on my production server simply bypassing the BasicAuth code which was not as intended
// A request to http://example.com/tracker was server ... still puzzling why :(
$cli = (php_sapi_name() == 'cli'); // || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0));

if (!$cli && ! (isset($_SERVER['PHP_AUTH_USER']) && ($_SERVER['PHP_AUTH_USER']==$username && $_SERVER['PHP_AUTH_PW']==$password))) {
    header('WWW-Authenticate: Basic realm="Our site to protect or press escape "');
    header('HTTP/1.0 401 Unauthorized');
    // The following HTML is spit out when the user presses cancel / escape
    echo '
<html>
  <head>
    <title>Our site</title>
    <link type="text/css" rel="stylesheet" media="all" href="/sites/all/themes/zen/zen/tabs.css?j" />
    # Add more theming files
  </head>
  <body class="front not-logged-in node-type-page one-sidebar sidebar-left" style="height:600px;">
    <div id="page-outer" style="height:600px;"><div id="page"><div id="page-inner">
    <p style="margin:30px">Text to show to the user when pressing escape.</p>
    </div></div></div>
    </body>
</html>
';
    exit;
}