Simple Login In PHP Without A Database (ok)

https://www.youtube.com/watch?v=C_Q33tOWejw

C:\xampp\htdocs\code\index.php

<?php  
	session_start();
	if(!$_SESSION['user']) {
		header("Location: login.php");
		exit();
	}
?>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>
<body>
	<p>Wellcome Home Page</p>
	<form action="protect.php" method="post">
  	<input type="hidden" name="logout" value="1"/>
  	<input type="submit" value="Logout"/>
	</form>
</body>
</html>

C:\xampp\htdocs\code\check.php

<?php
// (A) START SESSION
session_start();
// (B) HANDLE LOGIN
if (isset($_POST["user"]) && !isset($_SESSION["user"])) {
  // (B1) USERS & PASSWORDS - SET YOUR OWN !
  $users = [
    "lionel" => "123456",
    "jon" => "654321",
    "joy" => "987654"
  ];
  // (B2) CHECK & VERIFY
  if (isset($users[$_POST["user"]])) {
    if ($users[$_POST["user"]] == $_POST["password"]) {
      $_SESSION["user"] = $_POST["user"];
    }
  }
  // (B3) FAILED LOGIN FLAG
  if (!isset($_SESSION["user"])) { $failed = true; }
}
// (C) REDIRECT USER TO HOME PAGE IF SIGNED IN
if (isset($_SESSION["user"])) {
  header("Location: index.php"); // SET YOUR OWN HOME PAGE!
  exit();
}

C:\xampp\htdocs\code\login.php

<?php
// (A) LOGIN CHECKS
require "check.php";
// (B) LOGIN PAGE HTML ?>
<!DOCTYPE html>
<html>
  <head>
    <title>Login Page Demo</title>
    <link href="login.css" rel="stylesheet">
  </head>
  <body>
    <?php if (isset($failed)) { ?>
    <div id="bad-login">Invalid email or password.</div>
    <?php } ?>
    <form id="login-form" method="post" target="_self">
      <h1>PLEASE SIGN IN</h1>
      <label for="user">User</label>
      <input type="text" name="user" required/>
      <label for="password">Password</label>
      <input type="password" name="password" required/>
      <input type="submit" value="Sign In"/>
    </form>
  </body>
</html>

C:\xampp\htdocs\code\protect.php

<?php
// (A) START SESSION
session_start();
// (B) LOGOUT REQUEST
if (isset($_POST["logout"])) { unset($_SESSION["user"]); }
// (C) REDIRECT TO LOGIN PAGE IF NOT LOGGED IN
if (!isset($_SESSION["user"])) {
  header("Location: login.php");
  exit();
}

C:\xampp\htdocs\code\login.css

/* (A) WHOLE PAGE */
html, body { font-family: arial, sans-serif; }

/* (B) LOGIN FORM */
#login-form {
  padding: 20px;
  background: #f2f2f2;
  max-width: 320px;
  margin: 0 auto;}#login-form h1 {
  font-size: 1.5em;
  margin: 0;
  color: #9b9b8d;
}
#login-form label, #login-form input {
  box-sizing: border-box;
  display: block;
  width: 100%;
  margin-top: 10px;
}
#login-form input { padding: 10px; }
#login-form input[type=submit] {
  background: #ad4343;
  color: #fff;
  border: 0;
  cursor: pointer;
}

/* (C) INVALID LOGIN */
#bad-login {
  padding : 10px;
  margin-bottom: 10px;
  background: #ffe7e7;
  border: 1px solid #ff3e3e;
  color: #c10000;
  font-weight: bold;
}

Last updated