In this post, I am going to let you know how to create a Normal/Admin register and login using PHP and MySQL. I also provide features to logout from admin dashboard. I will use PHP session to maintain user visibility.
The Login system of the user helps to restrict the access of sensitive information or pages from unauthorized user.
The admin pages in the application are not accessible to normal users. To log in, all users (administrators and normal users) utilise the same form. Normal users are redirected to the index page after checking in, whereas admin users are redirected to the admin pages.
I am using SB Admin 2 theme.It’s a open source bootstrap based theme.
Registration and Login form in PHP and MySQL
Let’s build a user management system with two types of users: admins and regular users. I’ll save everything to a MySQL database.
Create the following files and directories in the xampp/htdocs(www if you’re using wamp) folder for a user-management application:
Whereas files are:
- index.php: This is the normal user’s home page.
- account.php: This file will contain user registration and login methods.
- admin/dashboard.php: This file will be used to display the admin user’s welcome dashboard page..
- header.php: This file contains information about the header theme.
- sidebar.php: This is a partial file that will display an html view of the ace admin sidebar.
- login.php: It will have a user sign-in view.
- register.php: This file provides user registration information; I use the same registration form for admins and regular users.
Create MySQL Connection Using PHP
We’ll start by creating a database called test. Also, using the SQL script below, create a login name table in this database:
CREATE TABLE `login` ( `id` int(11) NOT NULL, `first_name` varchar(50) NOT NULL, `last_name` varchar(50) NOT NULL, `email` varchar(50) NOT NULL, `password` varchar(50) NOT NULL, `user_type` enum('normal','admin','') NOT NULL DEFAULT 'normal', `status` enum('active','pending','deleted','') NOT NULL DEFAULT 'pending', `authtoken` varchar(250) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Create Connection Using PHP and MySQL
Let’s use PHP to make a connection with MySQL data. The following code was added to the top of the account.php
file.
// connect to database $db = mysqli_connect('localhost', 'root', '', 'test');
Create Partial header.php
We’ll make a header.php file and paste the code below into it. This file will contain all of the CSS and JS include paths. I also used the session start method at the top of the file to start a PHP session.
<head> <?php session_start(); ?> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>User Login and Register</title> <!-- Custom fonts for this template--> <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href="css/sb-admin-2.min.css" rel="stylesheet"> <!-- Bootstrap core JavaScript--> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="vendor/jquery-easing/jquery.easing.min.js"></script> <!-- Custom scripts for all pages--> <script src="js/sb-admin-2.min.js"></script> </head>
Add a link to the css/js files directly under the file’s head section.
Create Partial sidebar.php
We’ll make a sidebar.php file and paste the code below into it. This file has a sidebar menu option, which you can customize for both admins and regular users.
<!-- Sidebar --> <ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar"> <!-- Sidebar - Brand --> <a class="sidebar-brand d-flex align-items-center justify-content-center" href="index.html"> <div class="sidebar-brand-icon rotate-n-15"> <i class="fas fa-laugh-wink"></i> </div> <div class="sidebar-brand-text mx-3">SB Admin <sup>2</sup></div> </a> <!-- Divider --> <hr class="sidebar-divider my-0"> <!-- Nav Item - Dashboard --> <li class="nav-item"> <a class="nav-link" href="index.html"> <i class="fas fa-fw fa-tachometer-alt"></i> <span>Dashboard</span></a> </li> <!-- Divider --> <hr class="sidebar-divider"> <!-- Heading --> <div class="sidebar-heading"> Interface </div> <!-- Nav Item - Pages Collapse Menu --> <li class="nav-item"> <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo"> <i class="fas fa-fw fa-cog"></i> <span>Components</span> </a> <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> <h6 class="collapse-header">Custom Components:</h6> <a class="collapse-item" href="buttons.html">Buttons</a> <a class="collapse-item" href="cards.html">Cards</a> </div> </div> </li> </ul> <!-- End of Sidebar -->
Created Admin and User Registration
Using SB admin2 Theme Theme, we’ll first setup user and admin registration. Now, open register.php
in your preferred text editor and begin writing some code.
User and Admin Signup HTML
Create an HTML form that receives user input and saves it to the mysql login table. I’ve added the following code to this file:
<!DOCTYPE html> <html lang="en"> <?php include_once("header.php"); include('account.php') ?> <body id="page-top"> <!-- Page Wrapper --> <div id="wrapper"> <!-- Content Wrapper --> <div id="content-wrapper" class="d-flex flex-column"> <!-- Main Content --> <div id="content"> <div class="row"> <div class="col-lg-5 d-none d-lg-block bg-register-image"></div> <div class="col-lg-7"> <div class="p-5"> <div class="text-center"> <h1 class="h4 text-gray-900 mb-4">Create an Account!</h1> </div> <form class="user" method="post" action="register.php"> <p><?php echo display_error(); ?></p> <div class="form-group row"> <div class="col-sm-6 mb-3 mb-sm-0"> <input type="text" class="form-control form-control-user" name="fname" placeholder="First Name" value="<?php echo $fname; ?>"> </div> <div class="col-sm-6"> <input type="text" class="form-control form-control-user" name="lname" placeholder="Last Name" value="<?php echo $lname; ?>"> </div> </div> <div class="form-group"> <input type="email" class="form-control form-control-user" name="email" placeholder="Email Address" value="<?php echo $email; ?>"> </div> <div class="form-group"> <select name="user_type" id="user_type" class="form-control"> <option value="normal" selected>Normal</option> <option value="admin">Admin</option> </select> </div> <div class="form-group row"> <div class="col-sm-6 mb-3 mb-sm-0"> <input type="password" class="form-control form-control-user" name="pass" placeholder="Password"> </div> <div class="col-sm-6"> <input type="password" class="form-control form-control-user" name="c_pass" placeholder="Repeat Password"> </div> </div> <button type="submit" id="submit_btn" name="submit_btn" class="btn btn-primary btn-user btn-block"> Register Account </button> </form> <hr> <div class="text-center"> <a class="small" href="forgot-password.html">Forgot Password?</a> </div> <div class="text-center"> <a class="small" href="login.html">Already have an account? Login!</a> </div> </div> </div> </div> </div> <!-- End of Main Content --> <!-- Footer --> <footer class="sticky-footer bg-white"> <div class="container my-auto"> <div class="copyright text-center my-auto"> <span>Copyright © Your Website 2020</span> </div> </div> </footer> <!-- End of Footer --> </div> <!-- End of Content Wrapper --> </div> <!-- End of Page Wrapper --> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded" href="#page-top"> <i class="fas fa-angle-up"></i> </a> </body> </html>
At the top of the file, I’ve imported header.php and account.php. Create a POST type form request to submit user inputs to the server-side register()
procedure after the user presses the submit button.
Added Method to save User Form Data
Let’s add a method to the account.php
file that validates and saves data.
// variable declaration $fname = ""; $lname = ""; $email = ""; $errors = array(); // submit clicked if (isset($_POST['submit_btn'])) { signup(); } // escape string function parse_input($val){ global $db; return mysqli_real_escape_string($db, trim($val)); } // REGISTER USER function signup(){ // Global variables global $db, $errors, $fname, $lname, $email; // receive all input values from the form. $fname = parse_input($_POST['fname']); $lname = parse_input($_POST['lname']); $email = parse_input($_POST['email']); $pass = parse_input($_POST['pass']); $c_pass = parse_input($_POST['c_pass']); $user_type = parse_input($_POST['user_type']); // form validation if (empty($fname)) { array_push($errors, "first name is required"); } if (empty($lname)) { array_push($errors, "last name is required"); } if (empty($email)) { array_push($errors, "Email is required"); } if (empty($pass)) { array_push($errors, "Password is required"); } if ($pass != $c_pass) { array_push($errors, "The both passwords do not match"); } // register user if there are no errors in the form if (count($errors) == 0) { //encrypt the password $password = md5($pass); $query = "INSERT INTO login (first_name, last_name, email, user_type, password) VALUES('$fname', '$lname', '$email', '$user_type', '$password')"; mysqli_query($db, $query); // get id of the created user $logged_in_user_id = mysqli_insert_id($db); $_SESSION['user_info'] = getUserById($logged_in_user_id); $_SESSION['msg'] = "New user successfully created!!"; if (isset($_POST['user_type'])) { header('location: admin/dashboard.php'); }else{ header('location: index.php'); } } } function display_error() { global $errors; if (count($errors) > 0){ echo '<div class="alert alert-danger">'; foreach ($errors as $error){ echo $error .'<br>'; } echo '</div>'; } }
I’ve created three methods in the code above:
parse input– The mysqli real_escape_string()
method is used to parse user inputs.
signup– This method is used to process and save all form-posted payloads into the MySQL login table.
display error– This technique separates all errors and bids them with a div element, which is then printed on the user registration page.
Checkout other recommended tutorial of User Authentication in PHP,
- Simple PHP Login System Using MySQL and jQuery AJAX
- Simple Example of Laravel 5 Login System Using Sentry
- Website Login With Google or Yahoo/WordPress/OAL Account
- Email Verification With Activation Token In Laravel 5 Using Sentry
- Live Username Availability using PHP & jQuery
Created Login/Sign-In Using MySQL
I’ve already established a user registration feature; now I’ll add a user logged-in feature. I’ll take the user’s email address and password and transmit it to the login method. We’ll redirect you to the user page (normal user) or the admin dashboard page once the user credential has been validated (for admin users).
User and Admin Login HTML
Create an HTML form to collect user input and save it to the MySQL login table. I’ve added the following code to this file:
<!DOCTYPE html> <html lang="en"> <?php include_once("header.php"); include('account.php') ?> <body id="page-top"> <!-- Page Wrapper --> <div id="wrapper"> <!-- Content Wrapper --> <div id="content-wrapper" class="d-flex flex-column"> <!-- Main Content --> <div id="content"> <div class="row justify-content-center"> <div class="col-xl-10 col-lg-12 col-md-9"> <div class="card o-hidden border-0 shadow-lg my-5"> <div class="card-body p-0"> <!-- Nested Row within Card Body --> <div class="row"> <div class="col-lg-6 d-none d-lg-block bg-login-image"></div> <div class="col-lg-6"> <div class="p-5"> <div class="text-center"> <h1 class="h4 text-gray-900 mb-4">Welcome Back!</h1> </div> <form class="user" method="post" action="login.php"> <?php echo display_error(); ?> <div class="form-group"> <input type="email" class="form-control form-control-user" name="email" placeholder="Enter Email Address..." /> </div> <div class="form-group"> <input type="password" class="form-control form-control-user" name="password" placeholder="Password"> </div> <div class="form-group"> <div class="custom-control custom-checkbox small"> <input type="checkbox" class="custom-control-input" id="customCheck"> <label class="custom-control-label" for="customCheck">Remember Me</label> </div> </div> <button type="submit" class="btn btn-primary btn-user btn-block" name="login_btn"> Login </button> </form> <hr> <div class="text-center"> <a class="small" href="forgot-password.php">Forgot Password?</a> </div> <div class="text-center"> <a class="small" href="register.php">Create an Account!</a> </div> </div> </div> </div> </div> </div> </div> </div> </div> <!-- End of Main Content --> <!-- Footer --> <footer class="sticky-footer bg-white"> <div class="container my-auto"> <div class="copyright text-center my-auto"> <span>Copyright © Your Website 2020</span> </div> </div> </footer> <!-- End of Footer --> </div> <!-- End of Content Wrapper --> </div> <!-- End of Page Wrapper --> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded" href="#page-top"> <i class="fas fa-angle-up"></i> </a> <!-- Bootstrap core JavaScript--> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Core plugin JavaScript--> <script src="vendor/jquery-easing/jquery.easing.min.js"></script> <!-- Custom scripts for all pages--> <script src="js/sb-admin-2.min.js"></script> </body> </html>
I’ve added an account and header file at the top of the file, then generated a form with username and pass input fields. The login()
method receives the form credentials.
Added Method to Login User
In the account.php
file, we will add a login mechanism. This method is in charge of validating and establishing a session with the user.
// login() function if (isset($_POST['login_btn'])) { login(); } // LOGIN USER function login(){ global $db, $email, $errors; // grap form values $email = parse_input($_POST['email']); $password = parse_input($_POST['password']); // make sure form is filled properly if (empty($email)) { array_push($errors, "email is required"); } if (empty($password)) { array_push($errors, "Password is required"); } // attempt login if no errors on form if (count($errors) == 0) { $password = md5($password); $query = "SELECT * FROM login WHERE email='$email' AND password='$password' LIMIT 1"; $results = mysqli_query($db, $query); if (mysqli_num_rows($results) == 1) { // user found // check if user is admin or user $logged_in_user = mysqli_fetch_assoc($results); if ($logged_in_user['user_type'] == 'admin') { $_SESSION['user_info'] = $logged_in_user; header('location: admin/dashboard.php'); }else{ $_SESSION['user_info'] = $logged_in_user; header('location: index.php'); } }else { array_push($errors, "Wrong username/password entered"); } } } // return user info based on ID function getUserById($id){ global $db; $query = "SELECT * FROM login WHERE id=" . $id; $result = mysqli_query($db, $query); $user = mysqli_fetch_assoc($result); return $user; } function isLoggedIn() { if (isset($_SESSION['user_info'])) { return true; }else{ return false; } }
We’ve verified the user’s credentials, and if everything checks up, we’ll redirect based on the user’s type.
The getUserById()
method is used to retrieve information about a user based on their id. It returns user details, which are stored in the session variable.
The isLoggedIn()
method is used to determine whether a user is logged in or not. If the session contains a user info variable with a value set, the user is logged in; return True otherwise, False.
Logout Using PHP
We’ll implement a logout feature. The following code has been added to the account.php
file.
if (isset($_GET['logout'])) { session_destroy(); unset($_SESSION['user_info']); header("location: login.php"); }
How To Check Logged-in User is Admin
As you are aware, I have saved user information in the PHP session user info variable, which we will use to verify whether the user is an administrator or not. Add the following code to the account.php
file.
function isAdmin() { if (isset($_SESSION['user_info']) && $_SESSION['user_info']['user_type'] == 'admin' ) { return true; }else{ return false; } }
Conclusion
I hope you found this tutorial useful. We learned how to utilise PHP and MySQL to develop a user management system. For a user/admin, you can add further functionality such as listing and editing capabilities. You can adapt it to your requirements and use it in your projects. If you have any questions or concerns about this tutorial, please post them in the comments section below.
how can download all file
there is no any downloadable zip file, you need to create one by one file.
How do I create an admin page which the admin cant see all tables, edit the tables and if possible have full control of the table
You need to implement RBAC in your web app. OR you can use any framework like laravel that ll hv RBAC through libs