Simple Password Protected Page Content Using PHP

By Faruque Ahamed Mollick

I am again here with a new PHP coding tutorial and this is also a simple tutorial that may be useful for you.

Do you want a hidden web page or hidden content on your web page and make it accessible only for those peoples whom you give a specific password? Yes, you will set a password and peoples who know that password will be able to access it using the password.

In this post, I am going to give you the PHP code which will make a content or web page password protect. Only those peoples will able to access the content who know your password that you use to protect your page or content.

PHP code to make a page password protected

Below is the code that will do the task.

//Set the password
$password = "12345678pw"; 
//Let the user access protected content on page if the password match with the password that you have provided
if (isset($_POST["password"]) && ($_POST["password"]=="$password")) { ?>
  <h2 style="color: green;">Congratulations! You have successfully accessed the password protected content!</h2>
<?php }
//Display this content if the provided password is wrong
else{ 
//Show the wrong password notice
  if($_SERVER['REQUEST_METHOD'] == 'POST') {
    ?>
    <h2 style="color: red;">Sorry...! The password you have provided was Wrong!</h2>
  <?php } ?>
  <h2>Enter correct password to see the protected content on this page</h2>
 <p align="center"><font color="red">
 <form id ="myForm" method="post"><p align="center">
 <input name="password" type="password" size="25" maxlength="10"><input value="Submit" type="submit"></p>
 </form>
<?php 
 } 
?>

   <form action="<?php echo $_SERVER['SCRIPT_NAME'] ?>" method="post">
   <input type="submit" value="Save" />

First I have set a password and take it inside the variable¬†$password. Then create a form with the input field name “password“. And then I have created an if else condition which checks if the password submitted from the form input box match with my selected password or not.

If it matches with that password then it will show the text “Congratulations! You have successfully accessed the password protected content!” in a green colored text. Otherwise, it will show “Sorry…! The password you have provided was Wrong!” in a red colored text if the password provided is incorrect.

Tags:

Leave a Reply

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