Description
A developer's journey through code. I build, I break, and I write about it. Explore articles on modern software development, programming tips, and more.
In today's article, I will teach you an unconventional approach to building a login system in PHP without relying on traditional databases like MySQL or PostgreSQL, For security reasons it is not advisable to implement this in a working environment. Note, this article is for students who are learning PHP programming and yet to have a knowlege of how to connect and implement any of the traditional databases like MySQL or PostgreSQL but still want to have a feel of how databases work while relying only on PHP programming.
We will leverage log files to store user information and enhance security by blocking direct access to these log files using .htaccess. The system will consist of two main components: registration (handled by register.php) and login (handled by login.php). Upon successful login, users will be redirected to a personalized dashboard (dashboard.php). This is an idea that has been on my mind over a week now and today I have decided to practice it so read on as we explore together.
Step 1: Setting Up the Project Before getting started with the code, create the necessary files for your project: register.php: Handles user registration. login.php: Manages user login. dashboard.php: The user's dashboard.
Step 2: Using Log Files for User Storage Let us use a log file called users.txt to store registered user information. In register.php, we will capture user data and append it to the log file:
// register.php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$email = $_POST['email'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
// Store user information in the log file
file_put_contents('users.txt', "$email:$password\n", FILE_APPEND);
// Notify user if registration is successful
echo "Registration is successful";
exit();
}
Let me explain the code above for a better understanding especially to those new to PHP programming:
When a POST request happens (user submits the form), it retrieves the user's email and hashes the provided password using the password_hash function.
The user's email and hashed password are then appended to a log file named users.txt using the file_put_contents function, with the FILE_APPEND flag ensuring new information is added to the end of the file.
Finally, the script notifies the user of a successful registration using the echo function. The exit() function ensures that no further code is executed after the notification.
Please note that in a real-world scenario, additional security measures, such as input validation and sanitation, should be implemented. You can include an if statement in the register.php to check if a user is logged in already and redirect logged in users to dashboard.php instead of allowing logged in users to still visit the login.php, to achieve this use the session user created upon successful login to implement the if statement.
Step 3: Implementing the Login System In the login.php, we will check user credentials against the data stored in the users.txt:
// login.php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$email = $_POST['email'];
$password = $_POST['password'];
// Read user data from the log file
$users = file('users.txt', FILE_IGNORE_NEW_LINES);
foreach ($users as $user) {
list($storedEmail, $storedPassword) = explode(':', $user);
if ($email === $storedEmail && password_verify($password, $storedPassword)) {
// Set session user and redirect to the dashboard
$_SESSION['user'] = $email;
header('Location: dashboard.php');
exit();
}
}
// Invalid login, echo error message
echo 'Invalid login information.';
}
Let me explain the code above for a better understanding:
The script starts or resumes a session using session_start(). Sessions are used to persist data across different pages for the same user.
It checks if the HTTP request method is POST, meaning that the form has been submitted.
The user's input for email and password is obtained from the POST data.
The script reads user data from the users.txt file, where user information is stored in the format email:hashed_password.
It iterates through each line of the file, splitting the email and hashed password, and checks if the provided email matches any stored email and if the provided password matches the stored password after being verified with password_verify.
If a match is found, it sets the user in the session and redirects to the dashboard. If no match is found, it echoes an error message indicating invalid login information.
Note: ensure that the password hash algorithm and session management are secure.
Step 4: Securing Log Files with .htaccess The login system is not good without any form of security implemented, create an .htaccess file to secure your log files by blocking direct access:
# .htaccess
Order Allow,Deny
Deny from all
This ensures that users can't access the users.txt file directly via the URL.
Step 5: Redirecting to the Dashboard Include the following code at the beginning of login.php and register.php to redirect users to the dashboard if they are already logged in just like I pointed out ealier on this article:
// login.php and register.php
session_start();
// If a session user exists, redirect to the dashboard
if (isset($_SESSION['user'])) {
header('Location: dashboard.php');
exit();
}
We have successfully created a login system in PHP without using a traditional database. By utilizing log files and enhancing security with .htaccess, we have built a simple yet effective authentication system. Feel free to expand and customize this system based on your specific needs. If you have something to add or ask, do that in the comments section below.
Cookies improve user experience on SunshineIHCTS. By continuing to use this website, you consent to the use of cookies in accordance with the Privacy policy.
A developer's journey through code. I build, I break, and I write about it. Explore articles on modern software development, programming tips, and more.
Comments section
You need to be logged in to comment, Login or Register.Approved comments:
No comments yet! be the first to comment