In this article, you will learn how to create an authentication system with the help of HTML, PHP, and MySQL. Most of the websites are dynamic, and to get access to the restricted area user needs a registered user for that site. Therefore, they can log in to get access to members-only areas. The login authentication system is prevalent for any web application. It is likewise useful when we need to store data for users. It covers everything from the shopping sites, online-course sites, and membership sites, and so forth.
Creating a MySQL table
First of all, you will need to create a new database in MySQL. Please execute below SQL query inside your newly created database. It will create a new users database table.
CREATE TABLE `users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(75) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;
Create Signup Form
To access a restricted area, we will need to allow users to register a new account. We will create a PHP file with the name register.php. Please copy the below code and paste it in the register.php file.
<?php
require_once "config.php";
require_once "session.php";
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
$fullname = trim($_POST['name']);
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$confirm_password = trim($_POST["confirm_password"]);
$password_hash = password_hash($password, PASSWORD_BCRYPT);
if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
$error = '';
// Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s"
$query->bind_param('s', $email);
$query->execute();
// Store the result so we can check if the account exists in the database.
$query->store_result();
if ($query->num_rows > 0) {
$error .= '<p class="error">The email address is already registered!</p>';
} else {
// Validate password
if (strlen($password ) < 6) {
$error .= '<p class="error">Password must have atleast 6 characters.</p>';
}
// Validate confirm password
if (empty($confirm_password)) {
$error .= '<p class="error">Please enter confirm password.</p>';
} else {
if (empty($error) && ($password != $confirm_password)) {
$error .= '<p class="error">Password did not match.</p>';
}
}
if (empty($error) ) {
$insertQuery = $db->prepare("INSERT INTO users (name, email, password) VALUES (?, ?, ?);");
$insertQuery->bind_param("sss", $fullname, $email, $password_hash);
$result = $insertQuery->execute();
if ($result) {
$error .= '<p class="success">Your registration was successful!</p>';
} else {
$error .= '<p class="error">Something went wrong!</p>';
}
}
}
}
$query->close();
$insertQuery->close();
// Close DB connection
mysqli_close($db);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Register</h2>
<p>Please fill this form to create an account.</p>
<?php echo $success; ?>
<?php echo $error; ?>
<form action="" method="post">
<div class="form-group">
<label>Full Name</label>
<input type="text" name="name" class="form-control" required>
</div>
<div class="form-group">
<label>Email Address</label>
<input type="email" name="email" class="form-control" required />
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" required>
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-control" required>
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-primary" value="Submit">
</div>
<p>Already have an account? <a href="login.php">Login here</a>.</p>
</form>
</div>
</div>
</div>
</body>
</html>
Output for above code will look like below Image.
In the above code, we have created a simple registration HTML page. It has name, email, password, and confirm password as fields. All fields required in the registration form. We have used the default HTML5 attribute called required for validation. type=”email” validate email address format. Users can not create multiple accounts with the same email address. It will alert users that the account already registered with an email address. We have also added some validation using the HTML default attribute. You can always use some ready-made login forms to save time.
In the register.php file, we have included a config.php file. Now, Let’s create new config.php with the below code in it. config.php file used to connect our application to the MySQL database. Please change the name of the database which you chose when you created the database.
<?php
define('DBSERVER', 'localhost'); // Database server
define('DBUSERNAME', 'root'); // Database username
define('DBPASSWORD', ''); // Database password
define('DBNAME', 'demo'); // Database name
/* connect to MySQL database */
$db = mysqli_connect(DBSERVER, DBUSERNAME, DBPASSWORD, DBNAME);
// Check db connection
if($db === false){
die("Error: connection error. " . mysqli_connect_error());
}
?>
You can also see that we have included the session.php file. So, let’s create a new file session.php and paste the below code in it. This code will start the session and check if the user already logged in, if yes then the below script will redirect the user to the welcome.php file.
<?php
// Start the session
session_start();
// if the user is already logged in then redirect user to welcome page
if (isset($_SESSION["userid"]) && $_SESSION["userid"] === true) {
header("location: welcome.php");
exit;
}
?>
The register.php file will allow users to register themselves into the system. It will first check MySQL table if a user is already registered, if yes then alert the user with an error message if any record found in MySQL table with the same email address.
For security reasons, you need to make sure that the password not stored as plain text in the database. You can see that we have used password_hash() in-built PHP function. This function will create a new password hash using a secure one-way hashing algorithm.
After server-side validation, we will store all the data in the MySQL users table and alert the user with a success message.
Create Login Form
In this section, we will create a login.php file that will allow registered users to get access to a restricted area of the system. Please create a login.php file with the following code in it.
<?php
require_once "config.php";
require_once "session.php";
$error = '';
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
$email = trim($_POST['email']);
$password = trim($_POST['password']);
// validate if email is empty
if (empty($email)) {
$error .= '<p class="error">Please enter email.</p>';
}
// validate if password is empty
if (empty($password)) {
$error .= '<p class="error">Please enter your password.</p>';
}
if (empty($error)) {
if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
$query->bind_param('s', $email);
$query->execute();
$row = $query->fetch();
if ($row) {
if (password_verify($password, $row['password'])) {
$_SESSION["userid"] = $row['id'];
$_SESSION["user"] = $row;
// Redirect the user to welcome page
header("location: welcome.php");
exit;
} else {
$error .= '<p class="error">The password is not valid.</p>';
}
} else {
$error .= '<p class="error">No User exist with that email address.</p>';
}
}
$query->close();
}
// Close connection
mysqli_close($db);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Login</h2>
<p>Please fill in your email and password.</p>
<?php echo $error; ?>
<form action="" method="post">
<div class="form-group">
<label>Email Address</label>
<input type="email" name="email" class="form-control" required />
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" required>
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-primary" value="Submit">
</div>
<p>Don't have an account? <a href="register.php">Register here</a>.</p>
</form>
</div>
</div>
</div>
</body>
</html>
Below is the output for Login form.
In the above code, we have created a login form with some PHP script to confirm the user’s login credentials. On form submission, we will execute the SELECT SQL query to find the record in the database by email and password. If any record found from the database, then we will store the user’s details in session and redirect the user to the welcome.php file. If no record found, then the user alert with an error message.
Create a Welcome Page
Users will reach this page after a successful login. We will create a new welcome.php file with the following code in it. The welcome.php script will check if the user not logged in, then it will redirect the user to login.php file.
<?php
// start the session
session_start();
// Check if the user is not logged in, then redirect the user to login page
if (!isset($_SESSION["userid"]) || $_SESSION["userid"] !== true) {
header("location: login.php");
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome <?php echo $_SESSION["name"]; ?></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Hello, <strong><?php echo $_SESSION["name"]; ?></strong>. Welcome to demo site.</h1>
</div>
<p>
<a href="logout.php" class="btn btn-secondary btn-lg active" role="button" aria-pressed="true">Log Out</a>
</p>
</div>
</div>
</body>
</html>
The Logout Script
At last, we will create a logout.php file with the following code. Once the user clicks on the Log Out link, the above code will destroy all user’s session data, and redirect to the login.php file.
<?php
// Start the session
session_start();
// Destroy the session.
if (session_destroy()) {
// redirect to the login page
header("Location: login.php");
exit;
}
?>
Bottom Line
In this article, I explained how to create an authentication system using HTML, PHP, and MySQL. If you are not aware of HTML code, you can use login forms available on HTML5 website template sites. Once you understand the above tutorial, you can also add additional features like reset password, verify email, user’s profile, forgot password, etc.