How to Build a PHP Login Based on a User Account
Websites must have a user login from the client to perform basic tasks. Modern websites use this component most of the time to provide convenience for users.
Join the DZone community and get the full member experience.
Join For FreeWebsites must have a user login from the client to perform basic tasks. Modern websites use this component most of the time to provide convenience for users.
I will teach you today how to create a login system using PHP, MySQL, and Bootstrap (for the design).
PHP is the fundamental language for web development. Though it is old, using advanced programming and AI, you can create innovative applications in PHP.
PHP powers the famous CMS, WordPress, and Joomla, which are open-source OOP frameworks that can be used for numerous other applications.
PHP is the fundamental language for web development. With PHP, you can have a clean and easy-to-learn programming language. It can grow with the needs of developers, while it also has strong communities that are willing to provide support.
How to Create a Clean UI With Bootstrap for User Login
The first step was to create index.php with UI design and Bootstrap 5. We added Poppins Google Fonts for the design and CDN links wherever possible because the code becomes lightweight and less resource intensive.
Index file in PHP:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSS -->
<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="assets/css/style.css">
<title>Login</title>
</head>
<body>
<div class="container text-center d-flex align-items-center min-vh-100">
<div class="card mx-auto bg-info py-5" style="width: 25rem;">
<h1>Login</h1>
<div class="card-body">
<form action="" method="post">
<div class="mb-3">
<label for="email" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" name="email" required>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<button type="submit" class="btn btn-primary" name="login">Login</button>
</form>
</div>
</div>
</div>
<!-- JS -->
</body>
</html>
Later on, in the style.css file, I inserted a background image to give the background something more interesting to look at. However, this is just for legacy browsers that do not support modern web standards and could not view web images.
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Poppins', sans-serif;
background: #f1f1f1;
background: url("../img/email-pattern.webp");
}
Before working on the logic part of your program, we should create a database that will store users. MySQL would be a great choice because it's free and beginner-friendly. To create the database, go to PHPMyAdmin and set the name to something relevant.
Use the "Database" to create a table and name it "USERS." This should have four columns: ID, PASSWORD, EMAIL, and ACTIVE. Create a new row of columns and rows for each person with different values for each cell.
CREATE TABLE `users` (
`id` int(5) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`active` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
To implement the user login system, we will insert user login details into a SQL database first. Later on deployment, we will be using PHP for the signup process.
INSERT INTO `users` (`id`, `email`, `password`, `active`) VALUES
(1, 'test@gmail.com', '1234', 1);
Connect the MySQL database to PHP.
Our connection.php in Project:
<?php
$servername = "localhost"; // Enter Your severname here
$username = "root"; // Enter your MySQL database username here
$password = ""; // // Enter your MySQL database password here
$dbname = "ld_call"; // Enter your Database Name here
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Next, we code the login process step-by-step.
PHP User Login System Logic Revealed
Even though logic programming languages may seem intimidating, once we understand the reasoning behind the code, it becomes easier to write. The complexity of these programming languages is not due to the difficulty of writing or understanding the code but rather because they require us to think critically in order to make sense of them.
The first step is to break down the problem into smaller pieces, which are then iterated through. Pseudo-code is a way of writing for algorithms without needing to program in programming syntax. It’s usually broken up into lines that represent steps.
Code is the language used for programming. Pseudo-code is a simplified version, not actual code. They act as notes for programmers to follow to complete complex processes more quickly.
See how our login process is straightforward and easy to code.
In the long run, if you start getting into the habit of writing pseudo-code before writing a line of code, you will start loving coding. You will have no problem with longer pieces of programming code.
How to set up a user login procedure:
- The flow of the login form is filed by the user, who then clicks submit.
- We need to make sure that there aren't any backslashes or spaces after cleaning up the data.
- We securely encrypt your login information and compare it to our database for verification.
- Error messages a user may see.
- Here, we verify that the user's details have been saved.
- We also track our logged-in users in the session.
- Learn how to set up a logout process.
Don’t create pseudocode with too much code, and vice versa - don’t make the code too short.
Lets's go to code:
<?php
require_once("connection.php");
session_start();
function santize($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST['login'])) {
$email = santize($_POST['email']);
$password = santize($_POST['password']);
$sql = "SELECT id FROM users WHERE email = '$email' AND password = '$password' AND active = 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$_SESSION['login_active'] = [$email, $password];
header("Location: admin.php");
exit();
} else {
$_SESSION['errors'] = "Login Error! Check Email & Password";
header("Location: index.php");
exit();
}
}
?>
To show user login errors, I want to use a PHP session. Paste the code in the location that you want.
<?php if (isset($_SESSION['errors'])) : ?>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<?php
$message = $_SESSION['errors'];
unset($_SESSION['errors']);
echo $message;
?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
This is PHP code that can be inserted at the top of our index.php file to display if a user logs in successfully.
Here are what our Admin.php looks like:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="assets/css/style.css">
<title>Admin</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="">Admin</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0"></ul>
<div class="d-flex">
<a class="btn btn-outline-danger" href="logout.php">Logout</a>
</div>
</div>
</div>
</nav>
<div class="container">
<h1>Welcome to Admin</h1>
</div>
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
Add PHP code to admin.php that determines whether the login session is active or not. Otherwise, anyone will be able to access your page's admin file as there are no restrictions.
To protect other pages on the site from unauthorized access, use this code.
<?php
require_once("connection.php");
session_start();
if (!isset($_SESSION['login_active'])) {
header("Location: index.php");
exit();
}
?>
Once you’ve seen the whole process of building a user login system with PHP, MySQL, and Bootstrap 5, feel free to make use of this code.
Published at DZone with permission of Pawan Kumar. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments