PHP Password Protection – Alternative to HTACCESS

I was trying to put some password protection on a single file the other day using an htaccess file, but was getting all sorts of weird server errors. So I did some searching and a little research, and I figured out a way to mimic htaccess password protection with php.

// Check if Username and password correct or ask for them
if(($_SERVER['PHP_AUTH_USER'] == "myusername") AND
($_SERVER['PHP_AUTH_PW'] == "mypassword"))
{ ?>
Protected Content Here
<?php } else {
// Ask for username and password
header("WWW-Authenticate: " ."Basic realm=\"Protected Area\"");
header("HTTP/1.0 401 Unauthorized");
// Show failure text after several failed attempts
echo "This area is protected by a valid username and password";