3 Steps Simple Login System In PHP Without A Database

Welcome to a quick tutorial on how to create a simple login system in PHP without a database. So you just want a simple login authentication without too much difficult technical stuff?

We can create a simplified login system in PHP without a database, with the following general steps:

  1. Create an HTML login form.
  2. Store the user credentials in an array instead of the database. On login form submission, we check against the array – Set a session flag and redirect the user to the home page if verified.
  3. Finally, protect all other pages by checking against the session flag. Redirect the user to the login page if not signed in.

That is the gist of it, but let us walk through an actual example in this guide – Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Simple Login Useful Bits & Links
Tutorial Video The End

 

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • Set your own users and passwords in $users of 2-check.php, also where to redirect on successful login.
  • Protect all your pages by including 3-protect.php at the top.
  • Launch 1a-login.php in the web browser, that’s all.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SIMPLE PHP LOGIN SYSTEM (NO DATABASE)

All right let us now get started with the no-database login system.

 

STEP 1) HTML LOGIN PAGE

1a-login.php
<?php
// (A) LOGIN CHECKS
require "2-check.php";
 
// (B) LOGIN PAGE HTML
<?php if (isset($failed)) { ?>
<div id="bad-login">Invalid user 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>

This should be self-explanatory, just a simple HTML login form – When the login form is submitted, require "2-check.php" will take over and do the actual login processing.

 

 

STEP 2) PHP LOGIN PROCESS

2-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 = [
    "joe" => "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();
}
  1. Start the session, this is an essential part of login systems.
  2. As in the introduction, we keep the users in the $users array instead. We simply do a check against this array on login and register the user in $_SESSION['user'] on valid credentials.
  3. Redirect the user to the home page if properly signed in.

 

 

STEP 3) PROTECT ALL OTHER PAGES

3-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: 1a-login.php");
  exit();
}

To protect all the pages that require a valid login, simply require "3-protect.php" at the very top. Very simple snippet:

  • Remember that only logged-in users will have $_SESSION["user"]? We do a check here if this flag exists, and throw all users that are not logged in back to the login page.
  • For logging users out, simply create a form that submits $_POST["logout"] to itself (see below). This will unset($_SESSION["user"]) and redirect the user back to the login page.

 

 

EXTRA) HOW TO LOGOUT?

<form method="post">
  <input type="hidden" name="logout" value="1"/>
  <input type="submit" value="Logout"/>
</form>

Just add a simple form to post logout = 1, that will trigger if (isset($_POST["logout"])) { unset($_SESSION["user"]); }.

 

EXTRA) PROTECT YOUR PASSWORDS!

<?php
// GET ENCRYPTED PASSWORD
echo password_hash("YOUR-PASSWORD", PASSWORD_DEFAULT);

// TO VERIFY PASSWORD - MODIFY 2-CHECK.PHP (B2) 
if (password_verify($_POST["password"], $users[$_POST["user"]])) { .... }

Yes, it’s a simple system, but at least encrypt your passwords. It’s not as difficult as some may think…

 

USEFUL BITS & LINKS

That’s it for all the code, and here a section on the small extras that may be useful to you.

 

ALTERNATIVE – HTACCESS PASSWORD

This is an alternative way to add passwords without the use of PHP nor databases, but it will only work on Apache servers.

  1. Create a .htpasswd file to store the password. Just do a “htpasswd generator” search on the Internet, and that will give you plenty of generators online that you can use –
  2. Next, create a .htaccess file in the folder that you want to protect.
    • AuthType Basic
    • AuthName "Secret Ninja Zone"
    • AuthUserFile PATH/TO/.htpasswd
    • Require valid-user

 

LINKS & REFERENCES

 

TUTORIAL VIDEO

 

INFOGRAPHIC CHEAT SHEET

Login Without Database In PHP (Click To Enlarge)

 

THE END

Thank you for reading, and we have come to the end of this short guide. I hope that it has helped you with your project, and if you have anything to share, please feel free to comment below. Good luck and happy coding!

8 thoughts on “3 Steps Simple Login System In PHP Without A Database”

  1. I currently have a cPanel server, I have a domain site1.com we created the new website on the server using cPanel. The problem is that our script that was used to create the the site runs on the test site “site2.com” on the same cPanel server but does not run on the new site site1.com

    If have narrowed the issue down to this line 18 in EditPage.php: header(“Location: Login.php?Page=$PageToEdit”); The only difference I can se on the server is that “site1.com” is running “PHP7.4 PHP-FPM” in the cPanel and “site2.com” “PHP7.4” there is no way to turn “PHP-FPM” on or off in the cPanel so what is deciding to turn it on for some sites and not for the others? And why is it even needed make no sense. I’m a newbie so please be specific thanks!

    SERVER: cPanel Version 98.0 (build 6) – Apache Version 2.4.48 – PHP Version 7.4.22 – MySQL Version 10.3.31-MariaDB – Architecture x86_64 – Operating System linux – Kernel Version 3.10.0-1062.1.1.el7.x86_64

    PHP script that fails:

    // (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?Page=$PageToEdit”);
    die();
    }

    1. Here is the fix incase anyone else has this issue, Here is what I did:

      // (A) START SESSION
      // session_start();

      // (B) LOGOUT REQUEST
      if (isset($_POST[‘logout’])) { unset($_SESSION[‘user’]);
      session_destroy(); $_SESSION = []; }

      // (C) REDIRECT TO LOGIN PAGE IF NOT LOGGED IN
      if (!isset($_SESSION[‘user’])) {
      header(“Location: Login.php?Page=”.$PageToEdit);
      die();
      }

      1. I don’t plan to approve this comment at first, but it has educational value.

        1) Take note session_start() is commented off. Calling session_destroy() without starting a session first will literally throw a “Trying to destroy uninitialized session” warning.

        2) We do unset($_SESSION['user']) to log the user out without disturbing the rest of the sessions vars. Then, session_destroy() to clear all session data? Then, $_SESSION = [] to reassign an empty array to a session that is non-existant!? If you just want to clear out the entire session, why not just session_destroy()?

        Conclusion – The above “fix” makes zero sense. Knowledge is your best friend, follow up with https://code-boxx.com/sessions-in-php/.

Leave a Comment

Your email address will not be published. Required fields are marked *