Tech Arise

Web Development Tutorials & Resources

Skip to content
Menu
  • Home
  • Tutorials
    • PHP
    • Codeigniter
    • Node JS
  • How To
  • Live Demo

Simple Login & Registration system using PHP OOPS, MySQL and Bootstrap 4

Posted onLast Updated : February 3, 2019Last Updated : October 3, 2021By TechArise Team
Registration and Login is one of the primary module in any data management system. In this tutorial, we will learn how to develop a PHP Login script by using the PHP Object Oriented Programming concept with MySQL and Bootstrap 4. Using password authentication method password_hash() and password_verify() algorithm.We will cover this tutorial in easy steps with a live demo to develop complete Login and Registration. We will also provide to download source code of the live demo.
Step 1: Create MySQL Database and Tables
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
// Table structure for table `user`
CREATE TABLE `user` (
  `user_id` int(12) NOT NULL,
  `name` varchar(50) DEFAULT NULL,
  `user_name` varchar(50) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `status` int(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
 
// Indexes for table `user`
ALTER TABLE `user`
  ADD PRIMARY KEY (`user_id`),
  ADD UNIQUE KEY `email` (`email`);
 
// AUTO_INCREMENT for table `user`
ALTER TABLE `user`
  MODIFY `user_id` int(12) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
?>
Step 2: Create DBConnection Class
Create a Class file named “DBConnection.php” define constant and connect DB code.
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
<?php
/**
* @package Login & Registration
*
* @author TechArise Team
*
* @email  info@techarise.com
*  
*/
 
if(!isset($_SESSION))
    {
        session_start();
    }
date_default_timezone_set('Asia/Kolkata');
$root = "http://" . $_SERVER['HTTP_HOST'];
$root .= str_replace(basename($_SERVER['SCRIPT_NAME']), "", $_SERVER['SCRIPT_NAME']);
$constants['base_url'] = $root;
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'test_DB');
 
define('SITE_URL', $constants['base_url']);
define('HTTP_BOOTSTRAP_PATH', $constants['base_url'] . 'assets/vendor/');
define('HTTP_CSS_PATH', $constants['base_url'] . 'assets/css/');
define('HTTP_JS_PATH', $constants['base_url'] . 'assets/js/');
// windows path
//define('BASH_PATH', 'C:/xampp/htdocs/login-registration-system-using-php-oops-mysql/');
// ubuntu path
//define('BASH_PATH', '/var/www/login-registration-system-using-php-oops-mysql/');
// MAC path
define('BASH_PATH', '/Applications/XAMPP/htdocs/login-registration-system-using-php-oops-mysql/');
 
class DBConnection {
    private $_con;
    function __construct(){
        $this->_con = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD,DB_DATABASE);      
        if ($this->_con->connect_error) die('Database error -> ' . $this->_con->connect_error);
    }
    // return Connection
    function returnConnection() {
        return $this->_con;
    }
}
?>
Step 3: Create a Class file
Next create a file named User.php & include DBconnection file also:
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
<?php
/**
* @package Login & Registration
*
* @author TechArise Team
*
* @email  info@techarise.com
*  
*/
include "DBConnection.php";
class User
{
    protected $db;
    private $_userID;
    private $_name;
    private $_email;
    private $_username;
    private $_password;
    public function setUserID($userID) {
        $this->_userID = $userID;
    }
    public function setName($name) {
        $this->_name = $name;
    }
    public function setEmail($email) {
        $this->_email = $email;
    }
    public function setUsername($username) {
        $this->_username = $username;
    }
    public function setPassword($password) {
        $this->_password = $password;
    }
    public function __construct() {
        $this->db = new DBConnection();
        $this->db = $this->db->returnConnection();
    }
    // User registration Method
    public function userRegistration() {
        $password = $this->hash($this->_password);
        $query = 'SELECT * FROM user WHERE user_name="'.$this->_username.'" OR email="'.$this->_username.'"';          
        $result = $this->db->query($query) or die($this->db->error);            
        $count_row = $result->num_rows;        
        if($count_row == 0) {
            $query = 'INSERT INTO user SET user_name="'.$this->_username.'", password="'.$password.'", name="'.$this->_name.'", email="'.$this->_email.'", status="1"';            
            $result = $this->db->query($query) or die($this->db->error);                
            return true;
        } else {
            return false;
        }
    }
    
    // User Login Method
    public function doLogin() {    
        $query = 'SELECT user_id,password from user WHERE email="'.$this->_username.'" or user_name="'.$this->_username.'"';        
        $result = $this->db->query($query) or die($this->db->error);
        $user_data = $result->fetch_array(MYSQLI_ASSOC);
        print_r($user_data);
        $count_row = $result->num_rows;
        if ($count_row == 1) {
            if (!empty($user_data['password']) && $this->verifyHash($this->_password, $user_data['password']) == TRUE) {
                $_SESSION['login'] = TRUE;
                $_SESSION['user_id'] = $user_data['user_id'];
                return TRUE;
            } else {
                return FALSE;
            }
        }  
    }
    
    // get User Information
    public function getUserInfo() {
        $query = "SELECT user_id, name, email FROM user WHERE user_id = ".$this->_userID;
        $result = $this->db->query($query) or die($this->db->error);
        $user_data = $result->fetch_array(MYSQLI_ASSOC);
        return $user_data;
    }
    
    //get Session
    public function getSession() {
        if(!empty($_SESSION['login']) && $_SESSION['login']==TRUE) {
            return TRUE;
        } else {
            return FALSE;
        }
    }
    // logout method
    public function logout() {
        $_SESSION['login'] = FALSE;
        unset($_SESSION);
        session_destroy();
    }
 
        // password hash
    public function hash($password) {
        $hash = password_hash($password, PASSWORD_DEFAULT);
        return $hash;
    }
 
    // password verify
    public function verifyHash($password, $vpassword) {
        if (password_verify($password, $vpassword)) {
            return TRUE;
        } else {
            return FALSE;
        }
    }
}
?>
Step 4: Create registration file
Create a file named registration.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
<?php
function __autoload($class) {
    include "include/$class.php";
}
$user = new User();
 
if ($user->getSession()===TRUE) {
    header("location:home.php");
}
$status = '';
 
$errors = array();
//If our form has been submitted.
if(isset($_POST['submit'])){
    extract($_POST);
    //Get the values of our form fields.
    $fullname = isset($fullname) ? $fullname : null;
    $uemail = isset($uemail) ? $uemail : null;
    $uname = isset($uname) ? $uname : null;
    $password = isset($password) ? $password : null;
    //Check the name and make sure that it isn't a blank/empty string.
    if(strlen(trim($fullname)) === 0){
        //Blank string, add error to $errors array.
        $errors[] = "You must enter your fullname!";
    }
    if(strlen(trim($uname)) === 0){
        //Blank string, add error to $errors array.
        $errors[] = "You must enter your user name!";
    }
    if(strlen(trim($password)) === 0){
        //Blank string, add error to $errors array.
        $errors[] = "You must enter your password!";
    }
    //email address is valid.
    if(!filter_var($uemail, FILTER_VALIDATE_EMAIL)) {
        //$email is not a valid email. Add error to $errors array.
        $errors[] = "That is not a valid email address!";
    }
    //If our $errors array is empty, we can assume that everything went fine.
    if(empty($errors)){
        //insert data into database.
        $user->setName($fullname);
        $user->setEmail($uemail);
        $user->setUsername($uname);
        $user->setPassword($password);
        $register = $user->userRegistration();
        if ($register) {    
            $status = "<div class='alert alert-success' style='text-align:center'>Registration successful <a href='".SITE_URL."index.php'>Click here</a> to login</div>";
        } else {    
            $status = "<div class='alert alert-danger' style='text-align:center'>Registration failed. Email or Username already exits please try again.</div>";
        }
    }
}
 
?>
<?php
include('templates/header.php');
?>
<div class="row">
    <div class="col-lg-12">
        <h2>Simple Login & Registration system using PHP & MySQL</h2>                
    </div>
</div>
<div class="row">
    <div class="col-lg-12"><?php echo $status; ?></div>
</div>
<div class="row">
    <div class="col-lg-12"><ul><?php
        foreach ($errors as $value) {
            echo '<li style="color: red; font-size: 13px;">'.$value.'</li>' ;
        }
    ?></ul></div>
</div>
 
<div class="row">
    <div class="col-lg-12">
        <form action="" method="post" name="reg">    
            <div class="input-group mb-3">
                <div class="input-group-prepend">
                    <span class="input-group-text" id="basic-addon1"><i class="fa fa-user"></i></span>
                </div>
                <input type="text" name="fullname" class="form-control" placeholder="Full Name">
            </div>
            
            <div class="input-group mb-3">
                <div class="input-group-append">
                    <span class="input-group-text" id="basic-addon2"><i class="fa fa-user"></i></span>
                </div>
                <input type="text" name="uname" class="form-control" placeholder="Username">        
            </div>
            
            <div class="input-group mb-3">
                <div class="input-group-append">
                    <span class="input-group-text" id="basic-addon2"><i class="fa fa-envelope"></i></span>
                </div>
                <input type="text" name="uemail" class="form-control" placeholder="Email">        
            </div>
            
            <div class="input-group mb-3">
                <div class="input-group-append">
                    <span class="input-group-text" id="basic-addon2"><i class="fa fa-key"></i></span>
                </div>
                <input type="password" name="password" class="form-control" placeholder="******">        
            </div>
            
            <button type="submit" name="submit" class="float-right btn btn-primary">Register</button>
            <a href="<?php print SITE_URL; ?>index.php">Already registered? Click Here!</a>          
        </form>
    </div>
</div>
<?php
include('templates/footer.php');
?>
Step 5: Create a file
Create a view file named index.php(Login File)
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
<?php
function __autoload($class) {
    include "include/$class.php";
}
$msg = '';
$user = new User();
if (isset($_POST['submit'])) {
    extract($_POST);
    $user->setUsername($emailusername);
    $user->setPassword($password);  
    $login = $user->doLogin();
    if ($login) {          
       header("location:home.php");
    } else {            
        $msg = 'Wrong username or password';
    }
}
?>
<?php
include('templates/header.php');
?>
<div class="row">
    <div class="col-lg-12">
        <h2>Simple Login & Registration system using PHP & MySQL</h2>                
    </div>
</div>
<div class="row">
    <div class="col-lg-12">
        <?php if(!empty($msg)){
                echo '<div class="alert alert-danger">Wrong username or password</div>';
       } ?>    
    </div>
</div>
<div class="row">
    <div class="col-lg-12">
        <form action="" method="post" name="login">    
            <div class="input-group mb-3">
                <div class="input-group-prepend">
                    <span class="input-group-text" id="basic-addon1"><i class="fa fa-user"></i></span>
                </div>
                <input type="text" name="emailusername" class="form-control" placeholder="Username/Email">
            </div>
            
            <div class="input-group mb-3">
                <div class="input-group-append">
                    <span class="input-group-text" id="basic-addon2"><i class="fa fa-key"></i></span>
                </div>
                <input type="password" name="password" class="form-control" placeholder="******">        
            </div>
            
            <button type="submit" name="submit" class="float-right btn btn-primary">Login</button>
            <a href="<?php print SITE_URL; ?>registration.php">Register</a>          
        </form>
    </div>
</div>
<?php
include('templates/footer.php');
?>
Step 6: Create a file
Create a view file named home.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
<?php
function __autoload($class) {
    include "include/$class.php";
}
$user = new User();
if(!empty($_SESSION['user_id'])){
    $uid = $_SESSION['user_id'];
}
if ($user->getSession()===FALSE) {
   header("location:index.php");
}
if (isset($_GET['q'])) {
    $user->logout();
    header("location:index.php");
}
 
$user->setUserID($uid);
$userInfo = $user->getUserInfo();
?>
<?php
include('templates/header.php');
?>
<div class="row">
    <div class="col-lg-12">
        <h2>Simple Login & Registration system using PHP & MySQL</h2>                
    </div>
</div>
<div class="row">
    <div class="col-lg-12">
        <a href="<?php print SITE_URL; ?>home.php?q=logout" class="float-right btn btn-danger btn-sm">LOGOUT</a>
    </div>
</div>
<div class="row">
    <div class="col-lg-12">
        <p><strong>Full Name: </strong><?php print $userInfo['name'];?></p>        
        <p><strong>Email: </strong><?php print $userInfo['email'];?></p>
    </div>
</div>
<?php
include('templates/footer.php');
?>
Demo Download
Posted in: PHP, Tutorials, Web DesignTags: PHP OOPS Login, PHP OOPS Regisration

Post navigation

← Codeigniter Dependent country state city dropdown using jQuery Ajax with MySQL
Autocomplete Search with Dynamic Data using CodeIgniter and Bootstrap Typeahead →

Latest Articles

  • Library Management System in PHP and MySQL
  • NodeJS RESTfull APIs with Express and MySQL
  • How to get current date, given a timezone in PHP
  • Laravel 9 Registration and Login using MySQL
  • Convert HTML Content to PDF using JavaScript
  • Home
  •  |  
  • Contact Us
  •  | 
  • About Us

Copyright © 2011 - 2025 TECHARISE.COM All rights reserved.