Protecting staging environments

Is this PHP snippet inside the CMS index file a viable method of protecting staging?

I've seen a few ways of protecting test server environments from public (and Google crawling) consumption.

Back in 2009 - Ryan Masuga wrote this article on Devot EE using native ExpressionEngine functionality.

You can also limit access to an environment using an .htaccess file - either by username & password - as written by Jason Siffring last year.

You can also limit based on IP address - great if you know all of your client's IP addresses (not sure how I came to have this snippet by Jesse Bunch saved in TextExpander).

That said, I hate touching htaccess files. So then I started to look at other solutions and remembered an article by Acquia (behind a membership wall sadly) but it had something like this little snippet of PHP.

if($_SERVER['SERVER_ADDR'] == '127.0.0.1') {

  $username = 'username';
    $password = 'password';

  if (!(isset($_SERVER['PHP_AUTH_USER']) && ($_SERVER['PHP_AUTH_USER']==$username && $_SERVER['PHP_AUTH_PW']==$password)))  {
        header('WWW-Authenticate: Basic realm="This site is protected"');
        header('HTTP/1.0 401 Unauthorized');
        // Fallback message when the user presses cancel / escape
        echo 'Access denied';
      exit;
    }
}

My first thought is that having a username and password stored in a publicly accessible place isn't a great idea -- that said, if someone did get access, they're only going to see something that will later become public.

So I added this snippet to ExpressionEngine's index.php file (you could do it with Statamic, Craft or any other CMS). I set my staging server IP address and of course a different username and password.

Open to feedback on the good, bad and the ugly on this :)