In modern website applications, the registration system is commonly used in various modern applications, this is done to authenticate users to fully use their services. The login and registration system also has many benefits in your digital business, both membership or paid services.
Login or registration system is a security mechanism on the website to limit access to certain pages. In this tutorial, we will create a complete login or registration system along with a logout feature, password reset and a simple page to display data when successfully logged in using PHP. Let's start first by creating a table in the database.
1. First, create the database table first
Before entering the other stages, creating database tables is something important, used to store and read the data needed. Create a new database and run the query below to create a users table in the MySQL database.
CREATE TABLE users (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
); Copy and paste the line of code into the form in the SQL tab in phpmyadmin.
2. Create the database configuration file
In order for the database to be connected to the application, it takes a few lines of code to run it, create a new file called config.php to store data for the database, please copy and paste the lines of code below to continue.
Change the database username, database password and table name according to what you created yourself.
<?php // config.php
/*
* How to Create Login & Register System with PHP and MySQLi - Genelify
*/
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'test');
// Connect with database
$conn = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if ($conn === false) {
echo 'Error: failed to connected. ' . mysqli_connect_error();
exit();
} Change the database username, database password and table name according to what you created yourself.
3. Create a login system with PHP and HTML display the form
After finishing creating tables and configuring the database, we go to the next step, namely creating a login form or login system. At this stage, there is a form that functions to access the page by entering the required data such as name and password.
It is used to verify and authenticate data already stored in the database. If the name and password do not match those in the database, then access will be denied by the server. We are using Bootstrap as the CSS framework to handle the front end on this page.
To create this login form or login system, create a new php file and you can match the file name to login.php and just follow the code below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
body {
font: 14px sans-serif;
background: #efefef;
}
.wrapper {
width: 380px;
padding: 20px;
margin: 0 auto;
display: block;
margin-top: 60px;
background: #fff;
}
</style>
</head>
<body>
<div class="wrapper">
<h2>Login</h2>
<p>Please fill in the data needed to access your page.</p>
<?php if (!empty($login_err)) {
echo '<div class="alert alert-danger">' . $login_err . '</div>';
} ?>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control <?php echo (!empty($name_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $name; ?>">
<span class="invalid-feedback"><?php echo $name_err; ?></span>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>">
<span class="invalid-feedback"><?php echo $password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Login">
</div>
<p>Don't have an account? <a href="registration.php">Register here!</a>.</p>
</form>
</div>
</body>
</html> βAnd then follow the PHP code below right before the <!DOCTYPE html> tag.
<?php // login.php
/*
* How to Create Login & Register System with PHP and MySQLi - Genelify
*/
// Initialize session
session_start();
// Check if the user is already logged in, if so then it will be redirected to home
if (!empty($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
header('location: home.php');
exit();
}
// Add database configuration
require_once 'config.php';
// Define each variable with an empty value
$name = $password = '';
$name_err = $password_err = $login_err = '';
// Process the data if the form has been submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Name validation
$name_input = trim($_POST['name'] ?? '');
if ($name_input === '') {
$name_err = 'Please enter your name.';
} else {
$name = $name_input;
}
// Password validation
$password_input = trim($_POST['password'] ?? '');
if ($password_input === '') {
$password_err = 'Please enter your password.';
} else {
$password = $password_input;
}
// Validate credentials
if ($name_err === '' && $password_err === '') {
$sql = 'SELECT id, name, password FROM users WHERE name = ?';
$stmt = mysqli_prepare($conn, $sql);
if (!$stmt) {
echo 'Database error: ' . mysqli_error($conn);
exit();
}
// Bind variables into the statement as parameters
mysqli_stmt_bind_param($stmt, 's', $name);
// Execute statement
if (!mysqli_stmt_execute($stmt)) {
echo 'Seems like an error, please try again later!';
mysqli_stmt_close($stmt);
mysqli_close($conn);
exit();
}
// Save result
mysqli_stmt_store_result($stmt);
// Checks if the name is already in use
if (mysqli_stmt_num_rows($stmt) !== 1) {
$login_err = 'Incorrect username or password.';
mysqli_stmt_close($stmt);
mysqli_close($conn);
} else {
// Bind the result variable
mysqli_stmt_bind_result($stmt, $id, $name_db, $hashed_password);
if (mysqli_stmt_fetch($stmt)) {
// Perform password validation
if (password_verify($password, $hashed_password)) {
// If the password is successful, start into the session
session_regenerate_id(true);
$_SESSION['loggedin'] = true;
$_SESSION['id'] = $id;
$_SESSION['name'] = $name_db;
// Redirect user to home page
header('location: home.php');
exit();
}
// Displays an error if the password does not match
$login_err = 'Passwords do not match.';
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
} else {
// Close connection if validation failed
mysqli_close($conn);
}
}
?> All the data needed will later be entered into the session variable to allow access to the main page. When finished, try running it into the browser, the resulting output will be like this:
4. Create a registration system, along with HTML for the frontend
The next step is to create a registration system to send data to the server to be stored and used when the user logs in. This special page will display a form such as name, password and password confirmation that allows the user to register himself into the website application that we have created.
In this special code, we insert PHP and HTML code, the PHP code is used to process data entered by the user such as validation, storing data in the database and displaying errors if there are errors in filling out forms, duplication of names and so on. Then HTML is used to display the predefined form, we use Bootstrap as the CSS framework to handle the front end on this page.
Create a new file registration.php and just follow the syntax code below into the file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Registration</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
body {
font: 14px sans-serif;
background: #efefef;
}
.wrapper {
width: 380px;
padding: 20px;
margin: 0 auto;
display: block;
margin-top: 60px;
background: #fff;
}
</style>
</head>
<body>
<div class="wrapper">
<h2>Registration</h2>
<p>Please fill in the form below to continue.</p>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control <?php echo (!empty($name_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $name; ?>">
<span class="invalid-feedback"><?php echo $name_err; ?></span>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $password; ?>">
<span class="invalid-feedback"><?php echo $password_err; ?></span>
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-control <?php echo (!empty($confirm_password_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $confirm_password; ?>">
<span class="invalid-feedback"><?php echo $confirm_password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-secondary ml-2" value="Reset">
</div>
<p>Already have an account? <a href="login.php">Login here!</a></p>
</form>
</div>
</body>
</html> And then place the PHP code below right before the <!DOCTYPE html> tag.
<?php // registration.php
/*
* How to Create Login & Register System with PHP and MySQLi - Genelify
*/
// Call the config database
require_once 'config.php';
// Define each variable with an empty value
$name = $password = $confirm_password = '';
$name_err = $password_err = $confirm_password_err = '';
// Do it if the data has been entered into the form
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Name validation
$name_input = trim($_POST['name'] ?? '');
if ($name_input === '') {
$name_err = 'Please enter a name.';
} elseif (!preg_match('/^[a-zA-Z0-9_]+$/', $name_input)) {
$name_err = 'Names can only contain a combination of words, numbers or underscores.';
} else {
// Check if name already exists
$sql = 'SELECT id FROM users WHERE name = ?';
$stmt = mysqli_prepare($conn, $sql);
if (!$stmt) {
echo 'Database error: ' . mysqli_error($conn);
exit();
}
mysqli_stmt_bind_param($stmt, 's', $name_input);
if (mysqli_stmt_execute($stmt)) {
mysqli_stmt_store_result($stmt);
if (mysqli_stmt_num_rows($stmt) === 1) {
$name_err = 'This name is already registered!';
} else {
$name = $name_input;
}
} else {
echo 'There seems to be an error, please try again later.';
}
mysqli_stmt_close($stmt);
}
// Password validation
$password_input = trim($_POST['password'] ?? '');
if ($password_input === '') {
$password_err = 'Please enter a password.';
} elseif (strlen($password_input) < 6) {
$password_err = 'Password must be up to 6 characters long.';
} else {
$password = $password_input;
}
// Password confirmation
$confirm_input = trim($_POST['confirm_password'] ?? '');
if ($confirm_input === '') {
$confirm_password_err = 'Please confirm password.';
} elseif (empty($password_err) && $password_input !== $confirm_input) {
$confirm_password_err = 'Passwords do not match.';
} else {
$confirm_password = $confirm_input;
}
// Insert data if no errors
if ($name_err === '' && $password_err === '' && $confirm_password_err === '') {
$sql = 'INSERT INTO users (name, password) VALUES (?, ?)';
$stmt = mysqli_prepare($conn, $sql);
if (!$stmt) {
echo 'Database error: ' . mysqli_error($conn);
exit();
}
// Bind variables
$param_name = $name;
$param_password = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, 'ss', $param_name, $param_password);
if (mysqli_stmt_execute($stmt)) {
// Redirect if successful
header('location: login.php');
exit();
}
echo 'There seems to be an error, please try again later.';
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($conn);
}
?> We use password_hash to change the password into a hash algorithm to make it more secure, then match it with the password confirmation form to strengthen the registration system by using the password_verify function. When finished, try running it into the browser, the resulting output will be like this:

5. Create a logout system
This logout feature actually has a simple system, when the user successfully logs into the main page and the user logs out, then all data in the session variable will be deleted and the page will be redirected to the login page to re-enter. To add this logout feature, please copy and paste the syntax below into a new file called logout.php.
<?php // logout.php
/*
* How to Create Login & Register System with PHP and MySQLi - Genelify
*/
// Initialize session
session_start();
// Delete all variables in session
$_SESSION = [];
// Destroy session.
session_destroy();
// Redirect to login page
header('location: login.php');
exit();
6. Homepage section
This page is the main page when the user has successfully logged in and can do other things such as changing passwords and logging out. In this main page, we only display some simple text which indicates the user has successfully logged in.
And to avoid XSS attacks, we add the htmlspecialchars function to handle this. This function will change any form of script into special characters that cannot be executed by the browser. We are using Bootstrap as the CSS framework to handle the front end on this page. To add this main page, create a new file called home.php and the contents of the syntax are:
<?php // home.php
/*
* How to Create Login & Register System with PHP and MySQLi - Genelify
*/
// Initialize session
session_start();
// Check if the user is logged in, if not then redirect to the login page, but if yes then continue
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
header('location: login.php');
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome <?php echo htmlspecialchars($_SESSION['name']); ?> - Home</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
body {
font: 14px sans-serif;
text-align: center;
background: #efefef;
}
</style>
</head>
<body>
<h1 class="mt-5">Hello, <b><?php echo htmlspecialchars($_SESSION['name']); ?></b>. Welcome back.</h1>
<p class="mb-4">Successfully logged in, please if you want to change your password, you can click the reset password button below</p>
<p>
<a href="reset-password.php" class="btn btn-primary">Reset password</a>
<a href="logout.php" class="btn btn-danger ml-3">Logout</a>
</p>
</body>
</html> When finished, try running it into the browser, the resulting output will be like this:
7. Create a password reset system (optional)
Actually this feature is optional, but to complete the login and registration system, without the password reset feature it will be lacking, therefore we are adding this feature to complement it with other features.
The system in resetting this password is actually a simple system by changing the existing password with a new one on the main page after the user has successfully logged in, the new updated password still uses the hash algorithm to make it more secure. To add this password reset feature, move the syntax below into a new file called reset-password.php.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Reset Password</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
body{ font: 14px sans-serif; background: #efefef;}
.wrapper{ width: 380px; padding: 20px; margin:0 auto; displays: blocks; margin-top: 60px; background: #fff;}
</style>
</head>
<body>
<div class="wrapper">
<h2>Reset Password</h2>
<p>Please fill in the form below to replace the old password with a new one.</p>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
<div class="form-group">
<label>New password</label>
<input type="password" name="new_password" class="form-control <?php echo (!empty($new_password_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $new_password; ?>">
<span class="invalid-feedback"><?php echo $new_password_err; ?></span>
</div>
<div class="form-group">
<label>Confirm password</label>
<input type="password" name="confirm_password" class="form-control <?php echo (!empty($confirm_password_err)) ? 'is-invalid' : ''; ?>">
<span class="invalid-feedback"><?php echo $confirm_password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
<a class="btn btn-link ml-2" href="home.php">Cancel</a>
</div>
</form>
</div>
</body>
</html> And then place the PHP code below right before the <!DOCTYPE html> tag.
<?php // reset-password.php
/*
* How to Create Login & Register System with PHP and MySQLi - Genelify
*/
// Initialize session
session_start();
// Check if the user is logged in, if not redirect to the login page
if (empty($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
header('location: login.php');
exit();
}
// Call the config database
require_once 'config.php';
// Variable definition with empty value
$new_password = $confirm_password = '';
$new_password_err = $confirm_password_err = '';
// Process the data if the user submits the form
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Password validation
$new_password = trim($_POST['new_password'] ?? '');
if ($new_password === '') {
$new_password_err = 'Please enter your new password.';
} elseif (strlen($new_password) < 6) {
$new_password_err = 'Please enter a new password with a maximum of 6 characters';
}
// Validate password confirmation
$confirm_password = trim($_POST['confirm_password'] ?? '');
if ($confirm_password === '') {
$confirm_password_err = 'Please confirm your new password.';
} elseif (empty($new_password_err) && $new_password !== $confirm_password) {
$confirm_password_err = 'Passwords do not match.';
}
// Proceed if there are no errors
if ($new_password_err === '' && $confirm_password_err === '') {
// Prepare SQL statement
$sql = 'UPDATE users SET password = ? WHERE id = ?';
$stmt = mysqli_prepare($conn, $sql);
if (!$stmt) {
echo 'Database error: ' . mysqli_error($conn);
exit();
}
// Bind variables into the statement as parameters
$param_password = password_hash($new_password, PASSWORD_DEFAULT);
$param_id = $_SESSION['id'];
mysqli_stmt_bind_param($stmt, 'si', $param_password, $param_id);
// Execute
if (mysqli_stmt_execute($stmt)) {
// Password updated successfully, destroy session and redirect to login page
session_destroy();
header('location: login.php');
exit();
}
// If something went wrong
echo 'Seems like an error, please try again later.';
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($conn);
}
?> When finished, try running it into the browser, the resulting output will be like this:
Closing
That's a tutorial on making a simple login system using PHP, MySQL and Bootstrap. To complete all login systems, we add other features such as registration, logout, password reset, the main page to make it even more stable.