Password protect the page with PHP

November 3rd, 2009 by Alex Leave a reply »

Here we’ll take a look at some basic web page password protections. Basically, what we’ll need is to create a form with login and password, then check the sent data with the predefined one. If login/password matches, then we set a session variable and show the protected content:

<?
session_start();
 
$login = 'login';
$password = '123';
$message = '';
 
if (isset($_POST['login'])) {
  if ($_POST['login'] == $login && $_POST['password'] == $password) {
    $_SESSION['logged_in'] = 'ok';
    $message = 'You have successfully logged in.'; 
  } else {
    $message = 'Wrong login and/or password!'; 
  }
}
 
echo $message;
 
if ($_SESSION['logged_in']) {
  ?>
  <div><strong>Password protected content here.</strong></div>
  <?
} else {
  ?>
  <form action='password-protect.php' method='post'>
    Login: <input type='text' name='login' /><br />
    Password: <input type='password' name='password' /><br />
    <input type='submit' value='Login' />
  </form>
  <?
}
?>

This page can be found by searching for:

jquery password protectjquery password protect page



Comments are closed.