Password Tutorial

This information was taken and very slightly altered from the [Scott Page].


This is a demonstration of how to password protect a page. All users have the same password which is hardwired in php code. To give each user their own password the user’s user id and unique password must be stored in a database.

The idea is to check for a LoggedIn cookie set to TRUE at the beginning of a protected page. If the cookie doesn’t exist or is not true, the user is redirected to a login page (login.php) with a form asking for a password.

When the submit button is pressed on the login page, the user is directed back to login.php and the password is checked. If correct, the user is redirected to the website’s index.php page. Otherwise, the user is prompted to reenter the password and given an error message.

To logout, the user is directed to logout.php which clears the LoggedIn cookie.

Sample Code

  1. Place the following code in protect.php with nothing else. If the user doesn’t have a LoggedIn cookie set to true, they are redirected to the login page, login.php.
  2. [code lang="PHP"]
  3. Put the following line at the VERY TOP of any page you want to protect.
  4. [code lang="PHP"]
  5. Put the following in the VERY TOP of login.php, before the HTML tag. Change mypassword and mydomain as appropriate.
  6. [code lang="PHP"]
    if ($_POST['pass'] == 'mypassword')
    // SUCCESS: Redirect to your index.php page
    setcookie('LoggedIn', TRUE);
    else if (isset($_POST['pass']))
    // FAIL: Fall through to login_page
    setcookie('LoggedIn', FALSE);
    $errors = "Invalid password.";
    ?> [/code]
  7. Put the form where the user enters a password into the BODY of login.php.
  8. [code lang="PHP"]

  9. Put the following in a file called logout.php. To logout, make a link to logout.php.
    NOTE – I added the middle line to this code. It wasn’t working properly without it.
  10. [code lang="PHP"]

Author: Steph

Share This Post On

Pin It on Pinterest

Share This