Password Protect


This tutorial demonstrates how to create a basic password-protected page in PHP. Users must enter a correct username and password to access the protected content.

PHP Code
  1. <?php
  2.  
  3. $user = "USERNAME"; //Username to protected page
  4. $pass = "PASSWORD"; //Password to protected page
  5.  
  6.  
  7. if(isset($_POST['login']) && $_POST['username'] == $user && $_POST['password'] == $pass) { // If you entered the username/password correctly
  8.  
  9. echo "Top secret hidden content here!"; // Change content here
  10.  
  11. } else if(isset($_POST['login'])) { // If you didn't enter it correctly
  12. echo ('Incorrect username/password!');
  13. }
  14.  
  15. if(!isset($_POST['login'])) { // If you didn't log in it will show the login screen
  16. echo ('<form method="POST">
  17. <table>
  18. <tr><td>Username:</td><td><input type="text" name="username"></td></tr>
  19. <tr><td>Password:</td><td><input type="password" name="password"></td></tr>
  20. <tr><td><input type="submit" name="login" value="Log In"></td></tr>
  21. </table>
  22. </form>');
  23. }
  24.  
  25. ?>



How It Works



  • Define Credentials: Set the $user and $pass variables to the username and password you want to protect the page with.
  • Check Credentials: When the login form is submitted, the script checks the entered username and password against the predefined values.
  • Display Content or Errors: If the credentials match, the protected content is displayed. If not, an error message is shown.
  • Show Login Form: If the user hasn’t submitted the login form, the script displays the form for entering credentials.
kane0ner's Avatar
Author:
Views:
2,160
Rating:
There are currently no comments for this tutorial, login or register to leave one.