htaccess Password Protection
htaccess Password Protection
This tutorial will help you learn how to password protect your file quickly and easily in a few lines of code.
The code can be split up into three if-else statements. Let's take a look at what we will have to do in order to set up the password protection:
-
If the user has not been authenticated, then use the PHP header and ask for a username and password.
-
Else, if the user's name is "spoono" and the password is "spoono", log in. Inside here you would put all the code for the user.
-
Else tell them the user/password failed.
Finally, here is the PHP Code:
<?
//part 1
if (!isset($PHP_AUTH_USER))
{
header("WWW-Authenticate: Basic realm="Spoono Password."");
Header("HTTP/1.0 401 Unauthorized");
exit;
}
//part 2
else if(($PHP_AUTH_USER=="spoono") && ($PHP_AUTH_PW=="spoono"))
{
echo "You got in...";
//place the code for the whole user page in here
//you can also set up a redirect to the user page if you want
}
//part 3
else
{
echo "<html><body bgcolor=ffffcc>Faiiiiiiiil";
//fail try again
}
?>```
Enjoy!
ghost 18 years ago
lol commented after 1 min and 10 seconds :P and explaining some lines of code with more details would be better.. like for ** header("WWW-Authenticate: Basic realm="Spoono Password."");
Header("HTTP/1.0 401 Unauthorized");
exit;**
ghost 18 years ago
Why not just do this with htaccess? This is using HTTP Headers, not htaccess. This also probably shouldn't be done in PHP in this method, as htaccess recieves special read protection from the server- try it using PHP built as an apache module, using HTTP authentication, or just PHP.
ghost 18 years ago
thousandtoone.. you have a huge point.. wish I would have checked this before. I'll write a new one..
ghost 17 years ago
or you could go to yellowpipe and they have a htaccess file generator you just give the url of the file you want and give the password you want and there you go lol…..i have never "used and applied" this but i have played around with it….seems to work lol….peace