Password protect one section of a web page

Here is the code that you can use to password protect just one section of your web page.

First, open the web page in a text editor.

Next, copy and paste this code into the section that you want to password protect:

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

Make sure to define the username and password you want to use.

Finally, save the page as a PHP page (this is important!) and upload it to your website.

Note: If you are trying to make the entire webpage password protected, please refer to my previous post which covers how to password protect a web page

Meet the author

Libby Fisher is an experienced freelance web developer, recently relocated from Seattle to Boston, and passionate about developing websites that are both aesthetically appealing and intuitively usable - or as she prefers: "beautifully effective."

  • Pingback: Password protect a web page « I Code 4 You()

  • Annette

    Thank you for this code! It made adding a password so simple! :) I did need to add a check to it otherwise it gave me an error: Undefined index. This is the code I used to solve the problem:

    if ((isset($_POST[‘txtUsername’]) == false || isset($_POST[‘txtPassword’]) == false) ||

    ($_POST[‘txtUsername’] != $username || $_POST[‘txtPassword’] != $password)) { ?>

    i added this directly under the password. :)

    • http://www.thelibzter.com/ Libby

      Awesome, thanks Annette!