{{announcement.body}}
{{announcement.title}}

Create a Login System Using HTML, PHP, and MySQL

DZone 's Guide to

Create a Login System Using HTML, PHP, and MySQL

In this article, you will learn basic Registration and Login feature with the help of HTML, PHP, and MySQL.

· Web Dev Zone ·
Free Resource

This is a tutorial for creating a login system with the help of HTML, PHP, and MySQL. Your website needs to be dynamic and your visitors need to have instant access to it. Therefore, they want to log in as many times as possible. The login authentication system is very common for any web application. It allows registered users to access the website and members-only features. It is also helpful when we want to store information for users. It covers everything from shopping sites, educational sites, and membership sites, etc.

This tutorial is covered in 4 parts.

Table of Contents


  1. Sign up System
  2. Login System
  3. Welcome Page
  4. Logout Script

1) Building a Sign-up system

In this part, We will create a signup system that allows users to create a new account to the system. Our first step is to create a HTML registration form. The form is pretty simple to create. It only asks for a name, email, password, and confirm password. Email addresses will be unique for every user. Multiple accounts for the same email address are not allowed. It will show an error message to the users who try to create multiple accounts with the same email address.

Step 1: Creating Registration Form in HTML

We will create a PHP file named register.php with the following code in it. This is a simple HTML form with some basic validation. If you are not familiar with HTML then you can get it from many online sites who give ready-made html5 login form templates.

HTML
 




xxxxxxxxxx
1
40


 
1
<!DOCTYPE html>
2
<html lang="en">
3
    <head>
4
        <meta charset="UTF-8">
5
        <title>Sign Up</title>
6
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
7
    </head>
8
    <body>
9
        <div class="container">
10
            <div class="row">
11
                <div class="col-md-12">
12
                    <h2>Register</h2>
13
                    <p>Please fill this form to create an account.</p>
14
                    <form action="" method="post">
15
                        <div class="form-group">
16
                            <label>Full Name</label>
17
                            <input type="text" name="name" class="form-control" required>
18
                        </div>    
19
                        <div class="form-group">
20
                            <label>Email Address</label>
21
                            <input type="email" name="email" class="form-control" required />
22
                        </div>    
23
                        <div class="form-group">
24
                            <label>Password</label>
25
                            <input type="password" name="password" class="form-control" required>
26
                        </div>
27
                        <div class="form-group">
28
                            <label>Confirm Password</label>
29
                            <input type="password" name="confirm_password" class="form-control" required>
30
                        </div>
31
                        <div class="form-group">
32
                            <input type="submit" name="submit" class="btn btn-primary" value="Submit">
33
                        </div>
34
                        <p>Already have an account? <a href="login.php">Login here</a>.</p>
35
                    </form>
36
                </div>
37
            </div>
38
        </div>    
39
    </body>
40
</html>



The output of the above HTML form will look like this.

Sign Up

Sign Up


All the input fields are required by adding the "required" attribute which is the default HTML attribute. The use of type="email" will validate the email address provided by users and gives an error if the email address is not valid. For the registration form, we have used bootstrap for rapid development. If you want to save your time on HTML code you can always use some free html5 templates for your project.

Step 2: Creating the MySQL Database Table

You will need to create a new database with any suitable name you want. After that please execute the below SQL query to create the user's table inside your newly created MySQL database.

MySQL
 




xxxxxxxxxx
1


1
CREATE TABLE `users` (
2
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
3
  `name` varchar(75) NOT NULL,
4
  `password` varchar(255) NOT NULL,
5
  `email` varchar(100) NOT NULL,
6
  PRIMARY KEY (`id`),
7
  UNIQUE KEY `email` (`email`)
8
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;



Step 3: Creating Database Configuration File

Now, we have created the users table. Let's create a new PHP file named config.php to connect with the MySQL database. Paste the following code in the config.php file and change the database name to whatever you choose while creating the database.

PHP
 




xxxxxxxxxx
1
14


 
1
<?php
2
define('DBSERVER', 'localhost'); // Database server
3
define('DBUSERNAME', 'root'); // Database username
4
define('DBPASSWORD', ''); // Database password
5
define('DBNAME', 'demo'); // Database name
6
 
7
/* connect to MySQL database */
8
$db = mysqli_connect(DBSERVER, DBUSERNAME, DBPASSWORD, DBNAME);
9
 
10
// Check db connection
11
if($db === false){
12
    die("Error: connection error. " . mysqli_connect_error());
13
}
14
?>



Step 4: Creating a Session File

Let's create a file named session.php. In this file, we will start the session and check if a user is already logged in, if yes then we will redirect the user to welcome.php file.

PHP
 




xxxxxxxxxx
1
10


 
1
<?php
2
// Start the session
3
session_start();
4
 
          
5
// if the user is already logged in then redirect user to welcome page
6
if (isset($_SESSION["userid"]) && $_SESSION["userid"] === true) {
7
    header("location: welcome.php");
8
    exit;
9
}
10
?>



Step 5: Create Registration Form in PHP

Finally, it's time to create a PHP code that allows users to register their accounts into the system. This PHP code will alert users with an error if any user is already registered with the same email address.

Replace the following code in the register.php file.

PHP
 




xxxxxxxxxx
1
96


 
1
<?php
2
 
          
3
require_once "config.php";
4
require_once "session.php";
5
 
          
6
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
7
 
          
8
    $fullname = trim($_POST['name']);
9
    $email = trim($_POST['email']);
10
    $password = trim($_POST['password']);
11
    $confirm_password = trim($_POST["confirm_password"]);
12
    $password_hash = password_hash($password, PASSWORD_BCRYPT);
13
 
          
14
    if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
15
        $error = '';
16
        // Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s"
17
    $query->bind_param('s', $email);
18
    $query->execute();
19
    // Store the result so we can check if the account exists in the database.
20
    $query->store_result();
21
        if ($query->num_rows > 0) {
22
            $error .= '<p class="error">The email address is already registered!</p>';
23
        } else {
24
            // Validate password
25
            if (strlen($password ) < 6) {
26
                $error .= '<p class="error">Password must have atleast 6 characters.</p>';
27
            }
28
 
          
29
            // Validate confirm password
30
            if (empty($confirm_password)) {
31
                $error .= '<p class="error">Please enter confirm password.</p>';
32
            } else {
33
                if (empty($error) && ($password != $confirm_password)) {
34
                    $error .= '<p class="error">Password did not match.</p>';
35
                }
36
            }
37
            if (empty($error) ) {
38
                $insertQuery = $db->prepare("INSERT INTO users (name, email, password) VALUES (?, ?, ?);");
39
                $insertQuery->bind_param("sss", $fullname, $email, $password_hash);
40
                $result = $insertQuery->execute();
41
                if ($result) {
42
                    $error .= '<p class="success">Your registration was successful!</p>';
43
                } else {
44
                    $error .= '<p class="error">Something went wrong!</p>';
45
                }
46
            }
47
        }
48
    }
49
    $query->close();
50
    $insertQuery->close();
51
    // Close DB connection
52
    mysqli_close($db);
53
}
54
?>
55
<!DOCTYPE html>
56
<html lang="en">
57
    <head>
58
        <meta charset="UTF-8">
59
        <title>Sign Up</title>
60
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
61
    </head>
62
    <body>
63
        <div class="container">
64
            <div class="row">
65
                <div class="col-md-12">
66
                    <h2>Register</h2>
67
                    <p>Please fill this form to create an account.</p>
68
                    <?php echo $success; ?>
69
                    <?php echo $error; ?>
70
                    <form action="" method="post">
71
                        <div class="form-group">
72
                            <label>Full Name</label>
73
                            <input type="text" name="name" class="form-control" required>
74
                        </div>    
75
                        <div class="form-group">
76
                            <label>Email Address</label>
77
                            <input type="email" name="email" class="form-control" required />
78
                        </div>    
79
                        <div class="form-group">
80
                            <label>Password</label>
81
                            <input type="password" name="password" class="form-control" required>
82
                        </div>
83
                        <div class="form-group">
84
                            <label>Confirm Password</label>
85
                            <input type="password" name="confirm_password" class="form-control" required>
86
                        </div>
87
                        <div class="form-group">
88
                            <input type="submit" name="submit" class="btn btn-primary" value="Submit">
89
                        </div>
90
                        <p>Already have an account? <a href="login.php">Login here</a>.</p>
91
                    </form>
92
                </div>
93
            </div>
94
        </div>    
95
    </body>
96
</html>



Once user click on submit button it will check if $_SERVER["REQUEST_METHOD"] == "POST" and $_POST['submit'] a variable has been set. For security concerns, we always suggest not to store the password as plain text in the database. We have used password_hash() function which creates a new password hash using a strong one-way hashing algorithm.

The above PHP script will validate that no user is registered with the same email address and also validate the password. After validation is confirmed we store the user-provided information in the users' table and alert the user that registration was successful.

2) Building a Login System

In this part, we will create a login form to allow users to access the restricted area of the system. In our case, the restricted area is a welcome page which we will cover in the next part.

Step 1: Creating a Login Form in HTML

Below is the Login Form in HTML. Paste it in a file named login.php

HTML
 




xxxxxxxxxx
1
32


 
1
<!DOCTYPE html>
2
<html lang="en">
3
    <head>
4
        <meta charset="UTF-8">
5
        <title>Login</title>
6
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
7
    </head>
8
    <body>
9
        <div class="container">
10
            <div class="row">
11
                <div class="col-md-12">
12
                    <h2>Login</h2>
13
                    <p>Please fill in your email and password.</p>
14
                    <form action="" method="post">
15
                        <div class="form-group">
16
                            <label>Email Address</label>
17
                            <input type="email" name="email" class="form-control" required />
18
                        </div>    
19
                        <div class="form-group">
20
                            <label>Password</label>
21
                            <input type="password" name="password" class="form-control" required>
22
                        </div>
23
                        <div class="form-group">
24
                            <input type="submit" name="submit" class="btn btn-primary" value="Submit">
25
                        </div>
26
                        <p>Don't have an account? <a href="register.php">Register here</a>.</p>
27
                    </form>
28
                </div>
29
            </div>
30
        </div>    
31
    </body>
32
</html>



The output of the above code will look like this

Login

Login


Step 2: Creating a Login System in PHP

After creating the login form in HTML, we will write a code to validate login credentials. On form submit we will check that the email and password are filled. If they filled then we will execute a SELECT query to find the record in a database on the basis of email and password. If any record found, then we will store the "userID" in session and the user is redirected to the welcome.php file, otherwise, the user is alerted with an error message.

Let's replace the following code in the login.php file.

PHP
 




xxxxxxxxxx
1
81


 
1
<?php
2
 
          
3
require_once "config.php";
4
require_once "session.php";
5
 
          
6
 
          
7
$error = '';
8
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
9
 
          
10
    $email = trim($_POST['email']);
11
    $password = trim($_POST['password']);
12
 
          
13
    // validate if email is empty
14
    if (empty($email)) {
15
        $error .= '<p class="error">Please enter email.</p>';
16
    }
17
 
          
18
    // validate if password is empty
19
    if (empty($password)) {
20
        $error .= '<p class="error">Please enter your password.</p>';
21
    }
22
 
          
23
    if (empty($error)) {
24
        if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
25
            $query->bind_param('s', $email);
26
            $query->execute();
27
            $row = $query->fetch();
28
            if ($row) {
29
                if (password_verify($password, $row['password'])) {
30
                    $_SESSION["userid"] = $row['id'];
31
                    $_SESSION["user"] = $row;
32
 
          
33
                    // Redirect the user to welcome page
34
                    header("location: welcome.php");
35
                    exit;
36
                } else {
37
                    $error .= '<p class="error">The password is not valid.</p>';
38
                }
39
            } else {
40
                $error .= '<p class="error">No User exist with that email address.</p>';
41
            }
42
        }
43
        $query->close();
44
    }
45
    // Close connection
46
    mysqli_close($db);
47
}
48
?>
49
<!DOCTYPE html>
50
<html lang="en">
51
    <head>
52
        <meta charset="UTF-8">
53
        <title>Login</title>
54
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
55
    </head>
56
    <body>
57
        <div class="container">
58
            <div class="row">
59
                <div class="col-md-12">
60
                    <h2>Login</h2>
61
                    <p>Please fill in your email and password.</p>
62
                    <?php echo $error; ?>
63
                    <form action="" method="post">
64
                        <div class="form-group">
65
                            <label>Email Address</label>
66
                            <input type="email" name="email" class="form-control" required />
67
                        </div>    
68
                        <div class="form-group">
69
                            <label>Password</label>
70
                            <input type="password" name="password" class="form-control" required>
71
                        </div>
72
                        <div class="form-group">
73
                            <input type="submit" name="submit" class="btn btn-primary" value="Submit">
74
                        </div>
75
                        <p>Don't have an account? <a href="register.php">Register here</a>.</p>
76
                    </form>
77
                </div>
78
            </div>
79
        </div>    
80
    </body>
81
</html>



3) Creating a Welcome Page

Below is the code for the welcome.php file. Users will be redirected to this page after a successful login process. We have added some code at the top of the page to check if the user is not logged in, then redirect the user to the login page.

Let's create a welcome.php file and paste the following code in it.

PHP
 




xxxxxxxxxx
1
30


 
1
<?php
2
// start the session
3
session_start();
4
 
          
5
// Check if the user is not logged in, then redirect the user to login page
6
if (!isset($_SESSION["userid"]) || $_SESSION["userid"] !== true) {
7
    header("location: login.php");
8
    exit;
9
}
10
?>
11
<!DOCTYPE html>
12
<html lang="en">
13
    <head>
14
        <meta charset="UTF-8">
15
        <title>Welcome <?php echo $_SESSION["name"]; ?></title>
16
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
17
    </head>
18
    <body>
19
        <div class="container">
20
            <div class="row">
21
                <div class="col-md-12">
22
                    <h1>Hello, <strong><?php echo $_SESSION["name"]; ?></strong>. Welcome to demo site.</h1>
23
                </div>
24
                <p>
25
                    <a href="logout.php" class="btn btn-secondary btn-lg active" role="button" aria-pressed="true">Log Out</a>
26
                </p>
27
            </div>
28
        </div>
29
    </body>
30
</html>



4) The Logout Script

Finally, Let's create a logout.php file with the following code in it.

PHP
 




xxxxxxxxxx
1
11


 
1
<?php
2
// Start the session
3
session_start();
4
 
          
5
// Destroy the session.
6
if (session_destroy()) {
7
    // redirect to the login page
8
    header("Location: login.php");
9
    exit;
10
}
11
?>



Once the user clicks on the Log Out link, the above script, will be called to destroy the session and redirect the user to the login.php file.

Conclusion

In this tutorial, I explained how you can create a Login System using HTML, PHP, and MySQL. Once you understand how simple it is to create a login system you can add other features like reset password, forgot password, verify email address, edit user's profile, etc.

Topics:
html and css ,login ,php and mysql ,php application development ,sign up

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}