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?
The general steps to create a PHP login system without a database are:
- Create an HTML login form.
- Store the user credentials in an array. On login form submission, check against the array – Set a session flag, and redirect the user to the home page if verified.
- 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!
TABLE OF CONTENTS
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
EXAMPLE CODE DOWNLOAD
Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
SIMPLE PHP LOGIN SYSTEM (NO DATABASE)
All right let us now get started with the no-database login system.
TUTORIAL VIDEO
STEP 1) HTML LOGIN PAGE
<?php
// (A) LOGIN CHECKS
require "2-check.php";
// (B) LOGIN PAGE HTML
if (isset($failed)) { ?>
<div id="login-bad">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
<?php
// (A) START SESSION
session_start();
// (B) PROCESS 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"]]) && $users[$_POST["user"]] == $_POST["password"]) {
$_SESSION["user"] = $_POST["user"];
}
// (B3) FAILED LOGIN FLAG
if (!isset($_SESSION["user"])) { $failed = true; }
}
// (C) REDIRECT TO HOME PAGE IF SIGNED IN - SET YOUR OWN !
if (isset($_SESSION["user"])) {
header("Location: 4-dummy.php");
exit();
}
- Start the session, this is an essential part of login systems.
- As in the introduction. There is no database, so we keep the users in the
$users
array instead. Simply do a check against this array on login and register the user in$_SESSION["user"]
on a valid check. - Redirect the user to the home page if properly signed in.
STEP 3) PROTECT ALL OTHER PAGES
<?php
// (A) START SESSION
session_start();
// (B) LOGOUT REQUEST
if (isset($_POST["logout"])) {
session_destroy();
unset($_SESSION);
}
// (C) REDIRECT TO LOGIN PAGE IF NOT LOGGED IN
if (!isset($_SESSION["user"])) {
header("Location: 1-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:
- Start the session.
- For logging users out. Simply create a form that submits
$_POST["logout"]
to itself (see below), this will destroy and close the current session. - 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.
EXTRA) HOW TO LOGOUT?
<form method="post">
<input type="hidden" name="logout" value="1">
<input type="submit" value="Sign Out">
</form>
Just add a simple form to submit $_POST["logout"]=1
, this will trigger if (isset($_POST["logout"])) { CLOSE/DESTROY SESSION }
.
EXTRAS
That’s it for all the code, and here is 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 or databases, but it will only work on Apache servers.
- 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 – - 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
PROTECT YOUR PASSWORDS!
<?php
// GET ENCRYPTED PASSWORD
// COPY-PASTE ENCRYPTED PASSWORD INTO 2-CHECK.PHP (B1)
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…
ABLE TO ACCESS PROTECTED PAGES AFTER SIGNING OUT
Well, the culprit is probably the browser cache. For those who are new – Browsers usually keep a copy of pages to speed up loading time and for offline support. It’s a cool little mechanism, but it also causes problems with login/logout at times… A possible Javascript solution, credits to web.dev:
window.addEventListener("pageshow", event => {
if (event.persisted && !document.cookie.match(/PHPSESSID/)) {
// Force a reload if the user has logged out.
location.reload();
}
});
LINKS & REFERENCES
- Simple Ways To Encrypt Decrypt Passwords – Code Boxx
- Simple AJAX User Login Page (With PHP MySQL) – Code Boxx
- Cookies and Sessions in PHP – Code Boxx
- Apache htpasswd
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!
Thank you, Toh!
The explanations and the provided code are extremely helpful!
In my case, I noticed that I had to change the following line:
Instead of having the hidden value as “1” I had to set it as “logout”. For some reason, in some cases the value “1” was just not enough and I had to click the LogOut button twice.
Thanks a bundle!
Hey there, I’m having an issue. Could you contact me via discord? =REMOVED TO PROTECT “DOUGLAS” FROM SPAM=
Hi there! https://code-boxx.com/faq/#help “Contact me. I need help.”
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();
}
https://code-boxx.com/faq/#help
Sorry mate, I don’t offer free consultation and troubleshooting for personal projects and hosting. Good luck!
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();
}
I don’t plan to approve this comment at first, but it has educational value.
1) Take note
session_start()
is commented off. Callingsession_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!?3) If you just want to clear out the entire session, why not just
unset($_SESSION)
and/orsession_destroy()
?Conclusion – The above “fix” makes zero sense. Knowledge is your best friend, follow up with https://code-boxx.com/sessions-in-php/.
Works great! Thanks
Nice script… Thanks for sharing!