Password protect a web page

Here is the code you can use to password protect a web page quickly and easily.

If the web page you wish to password protect is an HTML page, open it in a text editor and save it as a PHP page.

Copy and paste this code at the very top of the page you have open in a text editor:

<code><?php  // Define your username and password  
$username = "someuser"; 
$password = "somepassword";  
if ($_POST&#91;'txtUsername'&#93; != $username || $_POST&#91;'txtPassword'&#93; != $password) {  ?>
<form name="form" method="post" action="<?php echo $_SERVER&#91;'PHP_SELF'&#93;; ?>">     
<p><label for="txtUsername">Username:</label>     
<br /><input type="text" title="Enter your Username" name="txtUsername" /></p>    
<p><label for="txtpassword">Password:</label>    
<br /><input type="password" title="Enter your password" name="txtPassword" /></p>     
<p><input type="submit" name="Submit" value="Login" /></p>  
<?php  }  else {  ?>  
<p>This is the protected page. Your private content goes here.</p> 
<?php  }  ?> </code>


First, you will obviously need to define the username and password that you want to use to protect the page.

Next, replace the text that says “This is the protected page…” in the code you just added to your page with the content of the web page that you want to be password protected.

You can password protect just one particular part of your web page if you want to by copying and pasting the code above into wherever on your web page you want to password protect, as long as the web page is a php page. See this post for an example of a web page with only part of it’s content password protected.

Note: if you are trying to password protect just one section of your web page, please refer to my next post on how to password protect part of a web page.