Categories
web

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";
}
?>

By natatkinson

Nate a web developer at Eastern Illinois University and occasionally adjunct-faculty at EIU teaching some courses in the School of Business. He lives in Champaign, IL with his wife and dogs Indiana ("we named the dog Indiana...") and Bear.

Leave a Reply

Your email address will not be published. Required fields are marked *