This site will look much better in a browser that supports web standards, but it is accessible to any browser or Internet device.


 

Dodo's Scripts Collection


Basic TutorialsBasic Tutorials

.htaccess Password Protection with PHP
This way of password protecting your file is simple. Although limited, it does its job very well if you just want to password protect a file. There is no cookie, mysql, javascript or text file involved here. All you have to do is some simple PHP code. Please understand that this .htaccess protection works only on a file (unless you do redirection) NOT on the whole directory. If you want to password protect a whole directory, please use this instead!
<?php
// Your private infomation
$popup_name = "My Secret File";
$username = "Username";
$password = "Password";


// if you didn't enter a user or pass
if (($_SERVER[PHP_AUTH_USER] != $username) || ($_SERVER[PHP_AUTH_PW] != $password))  
{  
	header("WWW-Authenticate: Basic realm=\"$popup_name\"");
	 
}      
// if the user and pass are correct
else 
{ 
	echo "Wow you may see my secret file here!"; 
   
}  

?>
Save as password1.php and enter "Username" and "Password" to log in! Now you may try different user & pass and watch what happens. Realize that the username and password ARE CASE SENSITIVE. So make sure when you tell people your log in, you give them in the correct case.

You may also redirect to another page after someone logs in. This require to name your "secret file" carefully. Just give a very random name so people may not guess what it is. I named mine "asdg7e552jdghx.php".
<?php
// Your private infomation
$popup_name = "My Secret File";
$username = "Username";
$password = "Password";
$redirect_file_name = "asdg7e552jdghx.php";


// if you didn't enter a user or pass
if (($_SERVER[PHP_AUTH_USER] != $username) || ($_SERVER[PHP_AUTH_PW] != $password))  
{  
	header("WWW-Authenticate: Basic realm=\"$popup_name\"");
	 
}      
// if the user and pass are correct
else 
{ 
	header("Location: $redirect_file_name"); 
   
}  

?>
Save it as password2.php and try it out! Please realize that the actual asdg7e552jdghx.php is not protected but it's just hard for people to guess the name to go there directly. To further protect your directory to MAKE SURE no one can view the directory index that contains your secret file. Put either a blank index file or a put
Options All -Indexes
In a blank text file and save as .htaccess (no .txt extension) and upload it to the directory where your secret file resides. The directory then should NOT BE accessible by from the web.
Back