Core PHP

Session Login and Logout

In this login and logout example, there are two distinct pages that are displayed: one for when the user is logged in and one for when the user is logged out. The login credentials for logging in use xoaxdotnet for the username and xoax for the password. The forms below are strictly visual and are not functional, but the actual script LoginLogout.php shown below is functional.

LoginLogout.php

<?php
  session_start();
  define("USERNAME","xoaxdotnet");
  define("PASSWORD","xoax");

  if (isset($_POST["login"])) {
  	CheckLogin();
  } elseif(isset($_GET["action"]) and $_GET["action"] == "logout") {
    SetLogout();
  } elseif(isset($_SESSION["username"])) {
    DisplayPage();
  } else {
    DisplayLoginForm();
  }

  function CheckLogin() {
    if (isset($_POST["username"]) and isset($_POST["password"])) {
      if ($_POST["username"] == USERNAME and $_POST["password"] == PASSWORD) {
        $_SESSION["username"] = USERNAME;
        session_write_close();
      } else {
        DisplayLoginForm("Sorry, that username and password do not match. Please try again.");
      }
    }
  }

  function SetLogout() {
    unset($_SESSION["username"]);
    session_write_close();
  }

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

  function DisplayLoginForm($sMessage="") {
    DisplayPageHeader();
?>
  <?php if ($sMessage) echo '<p style="background: #d33; color: white;
    padding: 0.2em;">'.$sMessage.'</p>' ?>

  <form action="LoginLogout.php" method="post">
    <div style="width: 30em;">
      <label style="display: block; float: left; clear: both; text-align: right;
        margin: 0.6em 5px 0 0; width: 40%;" for="username">Username</label>
      <input style="border: 1px solid #666; float: right; margin 1em 0 0 0; width: 57%;"
        type="text" name="username" id="username" value="" />
      <label style="display: block; float: left; clear: both; text-align: right;
        margin: 0.6em 5px 0 0; width: 40%;" for="password">Password</label>
      <input style="border: 1px solid #666; float: right; margin 1em 0 0 0; width: 57%;"
        type="password" name="password" id="password" value="" />
      <div style="clear: both;">
        <input style="border: 1px solid #666; float: right; margin 1em 0 0 0; width: 57%;
          width: auto;" type="submit" name="login" value="Login" />
      </div>
    <div>
  </form>
<?php
  }

function DisplayPageHeader() {
?>
    <h1 style="font-weight: bold; margin: 35px 0 14px; color: #666; font-size:
      1.5em;">An Example of Login and Logout Pages with Sessions</h1>
<?php
}
?>
 

Login

 

Logout

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.