How to Create a Sign-Up and Login System Using HTML, PHP, and MySQL

Katherine Petalio-Amar
7 min readDec 1, 2021
Photo by Aaron Burden on Unsplash

In this tutorial, you will learn how to create the basic Sign Up and Login System using HTML, PHP, and MySQL.

What to expect?

  • Create Database and Tables
  • Create PHP and MySQL Connection
  • Sign Up Page
  • Login Page
  • Welcome Page
  • Log Out Function

Prerequisite

Before we begin make sure you already have Apache Web Server, PHP, and MySQL. If you are working on your local PC/Laptop you can install either XAMPP (for Windows and Mac OS) or WAMP (for Windows only) or MAMP (for Mac OS only).

Create Database and Tables

Execute the following query on your PhpMyAdmin this will create the registration database and user table. If you already have a Database just execute the CREATE TABLE query.

CREATE DATABASE `db_registration` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;USE `db_registration`;CREATE TABLE `tbl_users` (
`user_id` int NOT NULL AUTO_INCREMENT,
`firstname` varchar(255) NOT NULL,
`lastname` varchar(255) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`timestamp` TIMESTAMP NOT NULL,
PRIMARY KEY (`user_id`)
);

Create PHP and MySQL Connection

After you successfully create the database and table, next is you need to create a PHP script to connect to the MySQL database server. Let’s name it config.php and put the following code inside it.

<?php
/***
Database Configuration File
Using Default MySQL Server Setting (user 'root' with no password)
***/
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define('DB_NAME', 'db_registration');

$db = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME); //Connect to MySQL Database

if($db === false){ //Check if Database is not connected
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
Note: Don't forget to replace the credentials according to your MySQL server setting.

Sign Up Page

Now, let’s create another PHP script named signup.php this will hold the code for registration. For easy HTML Styling let just used the very famous bootstrap, I just used jsDelivr CDN for bootstrap CSS.

Below are the codes for sign up, if you are new to PHP or Programming I’ll just list down some important parts of the codes (If you already know this just skip this part, and copy-paste the code if you like).

  • include — as you notice we included the previous file we created config.php, this is because the config.php holds your MySQL Connection Script which is very important for Sign Up and Login.
  • $_POST — is a PHP superglobal variable that is used to collect form data after submitting an HTML form with method=”post”. $_POST is also widely used to pass variables. (see)
  • isset() — this checks if the variable is empty.
  • trim() — this removes whitespaces of variable value.
  • $_SERVER — Server and execution environment information. (see)
  • array_filter() — removes empty value in an Array. ( But there are still other use of array_filter)
  • password_hash() — this will encrypt your password. (see) (Most NEW programmers always forget to encrypt their password when creating signup.)
  • mysqli_prepare() — this prepares the SQL statement. (see)
  • mysqli_stmt_bind_param() — this binds the variable to a prepared statement. (see)
  • mysqli_stmt_execute() — this will execute your query. (see)
  • mysqli_stmt_store_result() — this will hold the result after you execute your query. (see)
  • mysqli_stmt_num_rows() — this will return the number of rows from SQL statement set. (see)
  • mysqli_stmt_close() — this will close your previous SQL statement. (see)
  • mysqli_stmt_bind_result() — this will bind the result to a variable. (see)
  • mysqli_stmt_fetch() — this will get the data from your prepared SQL statement to bind the result variable. (see)
<?php
include 'config.php';

$fname = isset($_POST['firstname'])? trim($_POST['firstname']) : ""; //trim remove whitespaces, isset check if variable is empty
$lname = isset($_POST['lastname'])? trim($_POST['lastname']) : "";
$uname = isset($_POST['username'])? trim($_POST['username']) : "";
$pword = isset($_POST['password'])? trim($_POST['password']) : "";
$cpword = isset($_POST['confirmpassword'])? trim($_POST['confirmpassword']) : "";
$error = false; //declare error as false initially the form does not have error
if($_SERVER["REQUEST_METHOD"] == "POST"){ //Check if form is submitted

if(count(array_filter($_POST)) == count($_POST)){ //array_filter remove empty value in array, $_POST return array value, compare by counting if all $_POST fields has value
if(strlen($pword) >= 6){
if($pword != $cpword){
$msg = "Password did not match!";
$class = "alert-danger";
$error = true;
}
}else{
$msg = "Password must have atleast 6 characters.";
$class = "alert-danger";
$error = true;
}

if($error === false){
$query = "SELECT user_id FROM tbl_users WHERE username = ?";
if($stmt = mysqli_prepare($db, $query)){
mysqli_stmt_bind_param($stmt, "s", $uname); // Bind Variable this will help you avoid SQL injections , s for string
if(mysqli_stmt_execute($stmt)){
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
$msg = "Username is already taken.";
$class = "alert-danger";
$error = true;
}
}
else{
$msg = "Oops! Something went wrong. Please try again later.";
$class = "alert-danger";
}
mysqli_stmt_close($stmt);
}

}

if($error === false){
$query = "INSERT INTO tbl_users (firstname, lastname, username, password) VALUES (?, ?, ?, ?)";
if($stmt = mysqli_prepare($db, $query)){
mysqli_stmt_bind_param($stmt, "ssss", $fname, $lname, $uname, password_hash($pword, PASSWORD_DEFAULT)); //password_hash encrypt password

if(mysqli_stmt_execute($stmt)){
header("location: login.php");
}else{
$msg = "Oops! Something went wrong. Please try again later.";
$class = "alert-danger";
}
mysqli_stmt_close($stmt);
}
}


}else{
$msg = "All fields are required!";
$class = "alert-danger";
}
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<style>
.container{
padding: 50px;
}

.container form{
max-width: 400px;
margin:0 auto;
}
.container p{
padding-top:10px;
}
</style>
</head>
<body>
<div class="container">
<form action="" method="post">
<div class="alert <?php echo $class; ?> alert-dismissible fade show" role="alert" <?php echo (empty($msg)) ? "style='display:none;'" : ""; ?>>
<?php echo $msg ; ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<div class="mb-3">
<label for="FirstnameInput" class="form-label">First Name</label>
<input type="text" class="form-control" name="firstname" id="firstname" value="<?php echo $fname; ?>">
</div>
<div class="mb-3">
<label for="LastnameInput" class="form-label">Last Name</label>
<input type="text" class="form-control" name="lastname" id="lastname" value="<?php echo $lname; ?>">
</div>
<div class="mb-3">
<label for="UsernameInput" class="form-label">Username</label>
<input type="text" class="form-control" name="username" id="username" value="<?php echo $uname; ?>">
</div>
<div class="mb-3">
<label for="PasswordInput" class="form-label">Password</label>
<input type="password" class="form-control" name="password" id="password" value="<?php echo $pword; ?>">
</div>
<div class="mb-3">
<label for="ConfirmPasswordInput" class="form-label">Confirm Password</label>
<input type="password" class="form-control" name="confirmpassword" id="confirmpassword" value="<?php echo $cpword; ?>">
</div>

<button type="submit" class="btn btn-primary">Sign Up</button>
<p>Don't have an account? <a href="signup.php">Sign Up Now </a></p>
</form>
</div>
</body>
</html>

The code above has just a simple validation (since it is only basic I just made it simple), and it will look like this:

Login Page

Once you have successfully created your Sign Up Page, let’s now create your PHP Script for the login page let’s name it login.php. If you understand how the sign-up page script works, the code below will be easy for you. The important part here is the $_SESSION, validation of account if the account exists on the database.

We need to add session_start() on our login.php script, base on the word itself session is a particular activity within your website. You can store some sort of value within sessions.

The validation of the account will be consist of a username and password. The code below gets data from MySQL Database which matches the inputted username. If the username exists in MySQL Database we will now verify if the inputted password matches the password saved on the Database if it matches sessions will be created and you will be redirected to Welcome Page, otherwise, it will throw an error message.

<?php
include 'config.php';
session_start();
$uname = isset($_POST['username'])? trim($_POST['username']) : "";
$pword = isset($_POST['password'])? trim($_POST['password']) : "";

if($_SERVER["REQUEST_METHOD"] == "POST"){
$query = "SELECT user_id, firstname, lastname, password FROM tbl_users WHERE username = ?";
if($stmt = mysqli_prepare($db, $query)){
mysqli_stmt_bind_param($stmt, "s", $uname); // Bind Variable this will help you avoid SQL injections , s for string
if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
mysqli_stmt_bind_result($stmt, $id, $fname, $lname, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($pword, $hashed_password)){
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["uname"] = $uname;
$_SESSION["fname"] = $fname;
$_SESSION["lname"] = $lname;
header("location: welcome.php");
}else{
$msg = "Invalid password!";
$class = "alert-danger";
}
}
}else{
$msg = "Account does not exist.";
$class = "alert-danger";
}
}
else{
$msg = "Oops! Something went wrong. Please try again later.";
$class = "alert-danger";
}
mysqli_stmt_close($stmt);
}

}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<style>
.container{
padding: 50px;
}

.container form{
max-width: 400px;
margin:0 auto;
}
</style>
</head>
<body>
<div class="container">
<form action="" method="post">
<div class="alert <?php echo $class; ?> alert-dismissible fade show" role="alert" <?php echo (empty($msg)) ? "style='display:none;'" : ""; ?>>
<?php echo $msg ; ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<div class="mb-3">
<label for="UsernameInput" class="form-label">Username</label>
<input type="text" class="form-control" name="username" id="username" value="<?php echo $uname; ?>">
</div>
<div class="mb-3">
<label for="PasswordInput" class="form-label">Password</label>
<input type="password" class="form-control" name="password" id="password" value="<?php echo $pword; ?>">
</div>

<button type="submit" class="btn btn-primary">Log In</button>
</form>
</div>
</body>
</html>

The code above will look like this:

Welcome Page

This is just a simple page that says “Welcome” 😃 . The important part of this page is the validation of $_SESSION, you will only be able to visit this page if you successfully log in otherwise, you will be redirected to the login page.

Below is the script for Welcome Page, let’s just name it welcome.php.

<?php
session_start();

if($_SESSION["loggedin"] != true && empty($_SESSION["id"])){
header("location: login.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<style>
.container{
padding: 50px;
}

.container .name{
text-transform: capitalize;
font-size:20px;
}

.container .uname{
text-transform: lowercase;
font-size:14px;
font-weight:italic;
}
</style>
</head>
<body>
<div class="container">
WELCOME! <span class="name"><?php echo $_SESSION['fname']." ".$_SESSION['lname']; ?> </span> (<span class='uname'><?php echo $_SESSION['uname']; ?> </span>)

<a href="logout.php">Log Out</a>
</div>
</body>
</html>

Log Out Function

This page is purely PHP script, this will just destroy the session you have created on Login Page.

<?php
session_start();
$_SESSION = array(); // Unset all of the session variables

session_destroy(); // Destroy the session.

header("location: login.php"); // Redirect to login page
exit;
?>

Okay, Okay, I know you haven’t read the content above (but if you do Thank you so much 🥰 🥰 hope you understand my explanation), here is what your looking for 😂 😅

Download Script Here!

Github Link: https://github.com/khatzie/signup-login

If you have any questions, don’t hesitate to comment below it’s my pleasure to help you. 😉

--

--

Katherine Petalio-Amar

I'm a Software Developer with experience in Web Development and Mobile App Development and a bit knowledgeable in Server Management.