Login and Registration with Procedural PHP, MySQL

Table of Content

  1. Setting up a project folder
  2. Configure Database
  3. Database Connection
  4. Users File
  5. Init File
  6. Home Page
  7. Register Page
  8. Login Page
  9. Dashboard Page
  10. Logout
  11. Profile Data
  12. Setting
  13. Change Password

1. Setting up a project folder

In this part, we will be setting up the project folder which contains eight files and one folder. First of all, create five files and name them changepassword.php, dashboard.php, index.php, login.php, logout.php, profile.php, register.php, and setting.php. Secondly, create a folder and name them as a core, and inside that folder create three files namely db_connect.php, init.php, and users.php.

If you have followed the steps correctly then the working folder files structure would look like below:

2. Configure Database

Database Name: login_registration
Table Name: users
Table Column: id, username, password, first_name, last_name, contact, address, salt, active

Creating the database for this tutorial, you can either download the SQL Command at the end of this tutorial or copy and paste this following code into your MYSQL Database

1
2
3
4
5
6
7
8
9
10
11
12
13
14
CREATE DATABASE `login_registration`;
CREATE TABLE `login_registration`.`users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `first_name` varchar(255) NOT NULL,
  `last_name` varchar(255) NOT NULL,
  `contact` varchar(255) NOT NULL,
  `address` varchar(255) NOT NULL,
  `salt` text NOT NULL,
  `active` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

3. Database Connection

In this part, we will be creating and checking the database connection. Go to db_connect.php i.e. [core/db_connect.php]. If you have different database names for this tutorial then change the name of the database in this file which is highlighted below.

db_connect.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

4. Users File

This file contains the PHP function to manipulate the database operation. For instance, inserting the user’s credentials into the database, updating the user’s information, etc. This file is located at [core/users.php]. For now note that the file will be used to interact with the database, on later chapter this file will use.

5. Init File

In this part, we will start the session and include database connection files and users file. This file will be called at the login page, register page, change password page, etc.

init.php
1
2
3
4
5
6
7
8

6. Home Page

In this part, simple login and register link are provided for the user to interact with the system. For now, copy and paste these codes into the index.php and we will go through them afterward.

index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    

Firstly, at the beginning of the code includes the init file which was explained before. The logged_in function is invoked from the users.php, this function checks the user’s information is stored in the session and redirecting to the dashboard.php if its value is true.

Now go users.php i.e. [core/users.php] to create a logged_in function. This function verifies if the id is stored in the session by returning the boolean value.

users.php
1
2
3
4
5
6
7
function logged_in() {
    if(isset($_SESSION['id'])) {
        return true;
    } else {
        return false;
    }
}

The index page should look like below:

home_page_login

7. Register Users

In this part, we will create a registration form for users to enter the information. The submitted form will validate the required field information and calls the register users to function from the users.php and store it into the database. In this part, firstly we will create a user interface form and secondly, store the valid user’s information into the database by creating a function in the users.php.

Go to the register.php file to create a register form. For now, copy and paste these codes into the register.php file and go through them afterward.

register.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
";
    }
    if($lname == "") {
        echo " * Last Name is Required
"
;
    }
    if($username == "") {
        echo " * Username is Required
"
;
    }
    if($password == "") {
        echo " * Password is Required
"
;
    }
    if($cpassword == "") {
        echo " * Conform Password is Required
"
;
    }
    if($fname && $lname && $username && $password && $cpassword) {
        if($password == $cpassword) {
            if(userExists($username) === TRUE) {
                echo $_POST['username'] . " already exists !!";
            } else {
                if(registerUser() === TRUE) {
                    echo "Successfully Registered Login";
                } else {
                    echo "Error";
                }
            }
        } else {
            echo " * Password does not match with Conform Password
"
;
        }
    }
}
?>
    

"" method="POST">

    

        
        "text" name="fname" placeholder="First Name" autocomplete="off" value="" />
    
    

    

        
        "text" name="lname" placeholder="Last Name" autocomplete="off" value="" />
    
    

    

        
        "text" name="username" placeholder="Username" autocomplete="off" value="" />
    
    

    

        
        "password" name="password" placeholder="Password" autocomplete="off" />
    
    

    

        
        "password" name="cpassword" placeholder="Conform Password" autocomplete="off" />
    
    

    

        
        
    
Already Registered ? Click "login.php">login

In this file, the first line code includes the init.php file which was explained before. After that, the script checks if the user is already logged in by redirecting to the dashboard page. The script checks if the form is submitted and then stores the from input value into their appropriate variable name respectively.

Secondly, it validates the value by providing an error message. Thirdly, if the form validation is valid then it checks username by calling the user exists function and passing the username variable. If the username does not exist in the system then the script calls the register user function and displays a successful message. The user exists and register user function will be created in users.php file. Now go to the users.php file, copy and paste these codes and we will go through them afterward.

users.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
function userExists($username) {
    // global keyword is used to access a global variable from within a function
    global $connect;
    $sql = "SELECT * FROM users WHERE username = '$username'";
    $query = $connect->query($sql);
    if($query->num_rows == 1) {
        return true;
    } else {
        return false;
    }
    $connect->close();
    // close the database connection
}
function registerUser() {
    global $connect;
    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $username = $_POST['username'];
    $password = $_POST['password'];
    
    $salt = salt(32);
    $newPassword = makePassword($password, $salt);
    if($newPassword) {
        $sql = "INSERT INTO users (first_name, last_name, username, password, salt, active) VALUES ('$fname', '$lname', '$username', '$newPassword', '$salt' , 1)";
        $query = $connect->query($sql);
        if($query === TRUE) {
            return true;
        } else {
            return false;
        }
    } // /if
    $connect->close();
    // close the database connection
} // register user funtion
function salt($length) {
    return mcrypt_create_iv($length);
}
function makePassword($password, $salt) {
    return hash('sha256', $password.$salt);
}

The user exists function requires one parameter i.e. username. The variable connect is a database connection used as a global. After that its checks the username by return the boolean value.

The register user function does not require any parameter. This function calls the variable to connect as a global from the db_connetion file to execute the SQL query. This function also stores the form’s input value in the variable with the appropriate name. To secure the password, this function will encrypt the password value into hash. To do this, we will first create a salt variable and call the salt function and pass thirty-two (32) length to generate the mcrypt_create_iv value. That salt will be stored in the database to match with the password whenever users try to login to the system. After that, the make password function will have two parameters that are the password, and salt variable returning the password value which is encrypted into the sha256 hash format.

Lastly, the scripts check the new password variable and insert the user’s information into the database by return the boolean value.

The register page should look like below:

register

8. Login

In this part, we will create a login form for users to enter their login credentials. The login form submitted will validate the required field and checks if the username exists and if it exists then it calls the login function and stores the user’s information into the session. Firstly, we will create a user interface form and secondly, validate the required field, and login into the system and store it into the session.

Go to the login.php file to create a login form. For now, copy and paste these codes into the login.php file and we will go through them afterward.

login.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
";
    }
    if($password == "") {
        echo " * Password Field is Required
"
;
    }
    if($username && $password) {
        if(userExists($username) == TRUE) {
            $login = login($username, $password);
            if($login) {
                $userdata = userdata($username);
                $_SESSION['id'] = $userdata['id'];
                header('location: dashboard.php');
                exit();
                    
            } else {
                echo "Incorrect username/password combination";
            }
        } else{
            echo "username does not exists";
        }
    }
} // /if
?>
    

"" method="POST">

    

        
        "text" name="username" id="username" autocomplete="off" placeholder="Username" />
    
    

    

        
        "password" name="password" id="password" autocomplete="off" placeholder="Password" />
    
    

    

        
        
    
    
Not Registered ? Click "register.php">Register

In this file, it includes the init.php and checks if the users are logged in. After that, the scripts check if the form is submitted and if it’s true then it stores the username and password value into the respective variable name. The scripts validate the username and password value and display an appropriate message. If the validation is valid then the scripts check if the username value exists in the database by display an error message. If the username value exists in the database then it calls the login function with two parameters that are username and password variable. If the login function returns the true value then the script retrieves the user’s information by calling the user data function bypassing the username variable and store the user’s id into the session and redirecting to the dashboard.

The logged_in, the user exists function is already created in the registered chapter. In this part, the login, and user data function is new. For now, go to the users.php file, copy and paste these codes and we will go through them afterward.

users.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function login($username, $password) {
    global $connect;
    $userdata = userdata($username);
    if($userdata) {
        $makePassword = makePassword($password, $userdata['salt']);
        $sql = "SELECT * FROM users WHERE username = '$username' AND password = '$makePassword'";
        $query = $connect->query($sql);
        if($query->num_rows == 1) {
            return true;
        } else {
            return false;
        }
    }
    $connect->close();
    // close the database connection
}
function userdata($username) {
    global $connect;
    $sql = "SELECT * FROM users WHERE username = '$username'";
    $query = $connect->query($sql);
    $result = $query->fetch_assoc();
    if($query->num_rows == 1) {
        return $result;
    } else {
        return false;
    }
    
    $connect->close();
    // close the database connection
}

The login function requires two-parameter i.e. username and password. The variable connect is a global variable that holds the database connection and will be used to execute the SQL query. The user-data variable holds the user’s information. The script checks if the user data variable is not empty. If the user data variable is valid the script creates a new variable as a makePassword which holds the encrypted was of the by calling the made password (this function is defined in the previous part). After that, the script checks if the provided information matches with the database and returns the boolean value.

The user data function required one parameter i.e. username. The scripts fetch the user’s information through the username value and return the user’s information.

The login page should look like below :

login_registration_loginpage

9. Dashboard

The valid users will be redirected to this page. The dashboard contains the following pages and they are Profile, setting, change password, and logout. These lists will be listed in the unordered list with a link that will redirect to the selected page. For now, copy and paste these codes into the dashboard.php file and we will go through them afterward.

dashboard.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
    
    
  • Hello ,
    
    
    
    

This page will include the init file which was discussed in the early part. This page will also check if the user is not logged in the system then redirecting to the login page. The user data variable holds the user’s information through user id which was stored while logging the user id was stored into the session.

The not_logged_in function will return the session login status by returning the boolean value. The getUserDataByUserId function requires one parameter that is the user id. This function is invoked by the users.php, it retrieves the user information via user id which was stored in the session.

For not_logged_in, and getUserDataByUserId function, go to users.php, copy and paste these codes into the users.php file and we will go through them afterward.

users.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function not_logged_in() {
    if(isset($_SESSION['id']) === FALSE) {
        return true;
    } else {
        return false;
    }
}
function getUserDataByUserId($id) {
    global $connect;
    $sql = "SELECT * FROM users WHERE id = $id";
    $query = $connect->query($sql);
    $result = $query->fetch_assoc();
    return $result;
    $connect->close();
}

The not_logged_in function checks the id stored in the session by returning the boolean value. If the user id is stored in the session then returns true else false.

The getUserDataByUserId function requires one parameter that is id. This function selects the user’s information from the user’s table where id is equal to provided id and it returns in an associative array.

The dashboard page should look like below :

dashboard_login_registration_php

10. Logout

In this part, the logout page will call the logout function from the users.php file. The logout function will unset and destroy the session and redirects to the login page. For now, copy and paste these codes into the logout.php and we will go through afterward.

1
2
3
4
5
6
7

When evet the user clicks on the logout link the page will redirect to this page. This page contains the init file and logout function invoked from the user.php file. The main function of logout contains the logout function in the users.php file which is listed below. For now, copy and paste these codes into the users.php file and we will go through them afterward.

1
2
3
4
5
6
7
8
9
10
11
function logout() {
    if(logged_in() === TRUE){
        // remove all session variable
        session_unset();
        // destroy the session
        session_destroy();
        header('location: login.php');
    }
}

This function logout will call the logged_in function to check if the users are logged in the system. If the statement is true then the scripts will call the built-in PHP function session_unset and session_destoy to remove and destroy the session variable and it redirects to the login page.

11. Profile Data

In this part, we will be fetching the user’s information from the database through user id which is stored in the session. For now, copy and paste these codes into profile.php and we will go through them afterward.

        
        
    
profile.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
    
<h1>Profile Information</h1>
“1” style=”width:100%;”>
    
Username
    
        First Name
        
    
    
        Last Name
        
    
    
        Contact
        
    
    
        Address
        
    
 

This page includes the init.php file and checks if the user is not logged in to the system which calling the not_logged_in function to check the user’s status. The user’s information is retrieved by calling the getUserDataByUserId function which requires one parameter and stores the retrieve data into the user data variable.

The user’s information is displayed in the table layout as you can see below the image. The not_logged_in and getUserDataByUserId function explain before part.

The profile page should look like below :

login_registration_profile

12. Setting

In this part, the valid user should be to update their information. This page will display the user’s information which is stored in the system. For now, copy and paste these codes into the setting.php file and we will go through them afterward.

setting.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
";
    }
    if($lname == "") {
        echo " * Last Name is Required
"
;
    }
    if($username == "") {
        echo " * Username is Required
"
;
    }
    if($contact == "") {
        echo " * Contact is Required
"
;
    }
    if($address == "") {
        echo " * Address is Required
"
;
    }
    if($fname && $lname && $username && $contact && $address) {
        $user_exists = users_exists_by_id($_SESSION['id'], $username);
        if($user_exists === TRUE) {
            echo "username already exists
"
;
        } else {
            if(updateInfo($_SESSION['id']) === TRUE) {
                echo "Successfully Updated
"
;
            } else {
                echo "Error while updating the information";
            }
        }
    }
}
?>
    

"" method="POST">

    

        
        "text" name="username" id="username" placeholder="Username" value="">
    
    

    

        
        "text" name="fname" id="fname" placeholder="Fisrt Name" value="">
    
    

    

        
        "text" name="lname" id="lname" placeholder="Last Name" value="">
    
    

    

        
        "text" name="contact" id="contact" placeholder="Contact" value="">
    
    

    

        
        "text" name="address" id="address" placeholder="Address" value="">
    
    

    

              
    

This page includes the init file and checks the user’s logged-in status. The user’s information is retrieved by calling a getUserDataByUserId function which requires one parameter i.e. user id. The script checks if the form is submitted and stores the input value into the variable with their appropriate name. After that, the scripts validate the input field and if it is valid then it checks if the user’s name already exists in the system by calling the users_exists_by_id function which required two-parameter i.e. user id and username value. If the username does not exist in the system then the script calls the update info function which required one parameter that is user id and updates the information into the system by display a successful message.

The not_logged_in, getUserDataByUserId function has been explained at before chapter. The new function in this part is users_exists_by_id and updateInfor function is the new functionality in this part. For now, copy and paste these codes into the users.php file and we will go through them afterward.

users.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function users_exists_by_id($id, $username) {
    global $connect;
    $sql = "SELECT * FROM users WHERE username = '$username' AND id != $id";
    $query = $connect->query($sql);
    if($query->num_rows >= 1) {
        return true;
    } else {
        return false;
    }
    $connect->close();
}
function updateInfo($id) {
    global $connect;
    $username = $_POST['username'];
    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $contact = $_POST['contact'];
    $address = $_POST['address'];
    $sql = "UPDATE users SET username = '$username', first_name = '$fname', last_name = '$lname', contact = '$contact', address = '$address' WHERE id = $id";
    $query = $connect->query($sql);
    if($query === TRUE) {
        return true;
    } else {
        return false;
    }
}

The users_exists_by_id function requires two-parameter that is the user id and username value. This function calls the global to connect variable to execute the SQL queries. Then it selects the user’s information from the user’s table wich id is not equal to currently logged in user id because the username should not be equal to the current logged in username. After the query execution, the script checks if the username exists more than or equal to one by returning the boolean value.

The update info function requires one parameter that is the user id. This function stores the form input value into the variable with an appropriate name and executes the query.

The setting page should look like below :

setting

13. Change password

In this part, the logged-in users should be able to change the current password into the new password. The change password page should display a form that contains the current password, new password, and password again input filed. For now, copy and paste these codes into the changepassword.php file and we will go through them afterward.

            
                Current Password
            
            
                "password" name="currentpassword" autocomplete="off" placeholder="Current Password" />
            
changepassword.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
";
    }
    if($newpassword == "") {
        echo "New Password field is required
"
;
    }
    if($conformpassword == "") {
        echo "Conform Password field is required
"
;
    }
    if($currentpassword && $newpassword && $conformpassword) {
        if(passwordMatch($_SESSION['id'], $currentpassword) === TRUE) {
            if($newpassword != $conformpassword) {
                echo "New password does not match conform password
"
;
            } else {
                if(changePassword($_SESSION['id'], $newpassword) === TRUE) {
                    echo "Successfully updated";
                } else {
                    echo "Error while updating the information
"
;
                }
            }
            
        } else {
            echo "Current Password is incorrect
"
;
        }
    }
}
?>
    

"" method="POST">
    
        
        
        
            
                New Password
            
            
                "password" name="password" autocomplete="off" placeholder="New Password" />
            
        
        
            
                Conform Password
            
            
                "password" name="conformpassword" autocomplete="off" placeholder="Confrom Password" />
            
        
        
            
                
            
            
                "dashboard.php">
            
        
    

This page requires the init.php file and checks user logged-in status. The scripts check if the form submitted and stores the value into the variable with an appropriate name. The scripts validate the required field and if it is valid then firstly, the script checks if the current password is matching with users in the database. This is done by calling password match function which requires two parameters and that user id which is stored in the session and current password variable which holds the value of the current. If the current password matches the user details and scripts check if the password and password again value matches with each other. If the password matches the changePassword function and the new password information is stored into the user’s table.

The password match and changePassword function will be explained. For now, copy and paste these codes into the users.php file and we will go through them afterward.

users.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function passwordMatch($id, $password) {
    global $connect;
    $userdata = getUserDataByUserId($id);
    $makePassword = makePassword($password, $userdata['salt']);
    if($makePassword == $userdata['password']) {
        return true;
    } else {
        return false;
    }
    // close connection
    $connect->close();
}
function changePassword($id, $password) {
    global $connect;
    $salt = salt(32);
    $makePassword = makePassword($password, $salt);
    $sql = "UPDATE users SET password = '$makePassword', salt = '$salt' WHERE id = $id";
    $query = $connect->query($sql);
    if($query === TRUE) {
        return true;
    } else {
        return false;
    }
}

The password match function requires two-parameter that is user id and password value. This function fetches the user’s details from the database by the getUserDataByUserId function and makes an encrypted password by calling the make password function bypassing the password variable, and salt value from $userdata variables should be retrieved before. Now the scripts check the encrypted password value equals to the user information retrieved from the database.

The change password function requires two-parameter that is user id and password variable. This function creates a new salt value by calling the salt function and passing the thirty-two length parameter. Then it makes an encrypted password by calling the make Password function and updates the password information into the system.

The change password page should look like below :

changepassword

Source Code

Download Source Code

Download Database

Leave a Comment