PHP - Write program to Create a User Login System using session

Requirements

Write program to Create a User Login System using session

Sessions are a relatively secure way to build login systems.

The login username and password need to be sent from the browser when the user logs in, this only occurs during the login process.

For every other request, only the session ID is sent by the browser.

The following script allows the user to log in with a predefined username "Tom" and password "secret".

It then displays a welcome message, along with the option to logout.

Save it as login.php.

At the login page, log in with the username and password to view the welcome message, then log out to return to the login form.


<?php
session_start();
define("USERNAME" ,"Tom" );
define("PASSWORD" ,"secret" );

if (isset($_POST["login" ])) {
  login();
} elseif (isset($_GET[" action" ]) and $_GET[" action" ] =="logout" ) {
  logout();
} elseif (isset($_SESSION[" username" ])) {
  displayPage();
} else {
  displayLoginForm();
}

function login() {
  if (isset($_POST["username"]) and isset($_POST["password"])) {
    if ($_POST["username"] == USERNAME and $_POST["password"] == PASSWORD) {
      $_SESSION["username"] = USERNAME;
      session_write_close();
      header("Location: login.php");
    } else {
    displayLoginForm("Sorry, that username/password could not be found. Please try again.");
    }
  }
}

function logout() {
  unset($_SESSION["username"]);
  session_write_close();
  header("Location: login.php");
}

function displayPage() {
  displayPageHeader();
?>
    Welcome,  <strong>  <?php echo $_SESSION["username"] ?>  </strong> ! You are currently logged in. </p>
     <a href="login.php?action=logout"> Logout </a>  </p>
   </body>
 </html>
 <?php
}

function displayLoginForm($message="") {
  displayPageHeader();
?>
     <?php if ($message) echo'<p class="error">'. $message.'</p>'?>

     <form action="login.php"method="post">
       <div style="width: 30em;">
         <label for="username"> Username </label>
         <input type="text" name="username" id="username" value="" />
         <label for="password"> Password </label>
         <input type="password" name="password" id="password" value="" />
         <div style="clear: both;">
           <input type="submit" name="login" value="Login" />
         </div>
       </div>
     </form>
   </body>
 </html>
 <?php
}

function displayPageHeader() {
?>
 <html>
   <head>
     <title> A login/logout system </title>
     <style type="text/css">
   .error { background: #d33; color: white; padding: 0.2em; }
     </style>
   </head>
   <body>
     <h1> A login/logout system </h1>
 <?php
}
?>

Related Exercise