Registration and Login System with PHP and MySQL

The login system allows the user to create and log in to their account for accessing the website content. The login system is a key feature for every membership website. If you want to restrict access to the website content and allow only the logged-in user to access the content, user login functionality need to be implemented. User registration and login system can be integrated easily with PHP and MySQL. In this tutorial, we’ll show you how to build a secure login system with PHP and MySQL.

In this PHP login system script, we will implement the following functionality with PHP and MySQL.

  • Registration to create a user account.
  • User account validation.
  • User authentication with PHP SESSION.
  • User account view.

Before getting started to build User Login System with PHP, take a look at the file structure.

php_login_system_with_mysql/
├── User.class.php
├── userAccount.php
├── index.php
├── registration.php
└── css/
    └── style.css

Create Database Table

A table is required to store account details in the database. The following SQL creates a users table in the MySQL database.

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Block',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

User Class (User.class.php)

User Class handles all the database-related operations (Connect, Fetch and Insert) with PHP and MySQL.

  • At the beginning, specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName) as per the MySQL database credentials.
  • __construct() – Connect the database using the specified MySQL credentials.
  • getRows() – Fetch records from the database based on the conditions.
  • insert() – Insert data into the database.
<?php 
/*
 * User Class
 * This class is used for database related (connect fetch, and insert) operations
 * @author    CodexWorld.com
 * @url       https://www.codexworld.com
 * @license   https://www.codexworld.com/license
 */
class User{
    private 
$dbHost     "localhost";
    private 
$dbUsername "root";
    private 
$dbPassword "root";
    private 
$dbName     "codexworld";
    private 
$userTbl    "users";
    
    public function 
__construct(){
        if(!isset(
$this->db)){
            
// Connect to the database
            
$conn = new mysqli($this->dbHost$this->dbUsername$this->dbPassword$this->dbName);
            if(
$conn->connect_error){
                die(
"Failed to connect with MySQL: " $conn->connect_error);
            }else{
                
$this->db $conn;
            }
        }
    }
    
    
/*
     * Returns rows from the database based on the conditions
     * @param string name of the table
     * @param array select, where, order_by, limit and return_type conditions
     */
    
public function getRows($conditions = array()){
        
$sql 'SELECT ';
        
$sql .= array_key_exists("select",$conditions)?$conditions['select']:'*';
        
$sql .= ' FROM '.$this->userTbl;
        if(
array_key_exists("where",$conditions)){
            
$sql .= ' WHERE ';
            
$i 0;
            foreach(
$conditions['where'] as $key => $value){
                
$pre = ($i 0)?' AND ':'';
                
$sql .= $pre.$key." = '".$value."'";
                
$i++;
            }
        }
        
        if(
array_key_exists("order_by",$conditions)){
            
$sql .= ' ORDER BY '.$conditions['order_by']; 
        }
        
        if(
array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
            
$sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit']; 
        }elseif(!
array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
            
$sql .= ' LIMIT '.$conditions['limit']; 
        }
        
        
$result $this->db->query($sql);
        
        if(
array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){
            switch(
$conditions['return_type']){
                case 
'count':
                    
$data $result->num_rows;
                    break;
                case 
'single':
                    
$data $result->fetch_assoc();
                    break;
                default:
                    
$data '';
            }
        }else{
            if(
$result->num_rows 0){
                while(
$row $result->fetch_assoc()){
                    
$data[] = $row;
                }
            }
        }
        return !empty(
$data)?$data:false;
    }
    
    
/*
     * Insert data into the database
     * @param string name of the table
     * @param array the data for inserting into the table
     */
    
public function insert($data){
        if(!empty(
$data) && is_array($data)){
            
$columns '';
            
$values  '';
            
$i 0;
            if(!
array_key_exists('created',$data)){
                
$data['created'] = date("Y-m-d H:i:s");
            }
            if(!
array_key_exists('modified',$data)){
                
$data['modified'] = date("Y-m-d H:i:s");
            }
            foreach(
$data as $key=>$val){
                
$pre = ($i 0)?', ':'';
                
$columns .= $pre.$key;
                
$values  .= $pre."'".$val."'";
                
$i++;
            }
            
$query "INSERT INTO ".$this->userTbl." (".$columns.") VALUES (".$values.")";
            
$insert $this->db->query($query);
            return 
$insert?$this->db->insert_id:false;
        }else{
            return 
false;
        }
    }

}

Registration, Login, and Logout Request Processing (userAccount.php)

This server-side script handles the registration, authentication, and logout request which comes from index.php and registration.php. The User Class (User.class.php) is used to fetch and insert user account data from/to the database.

  • signupSubmit – If sign up request is submitted, input data is inserted in the database after the validation.
  • loginSubmit – If login request is submitted, the system checks if any record is exists in the database with the given email and password.
  • logoutSubmit – If logout request is submitted, system log the user out from their account.
  • PHP SESSION is used to hold the login status of the user.
<?php 
// Start session
session_start();

// Load and initialize user class
include 'User.class.php';
$user = new User();

$postData $statusMsg $valErr '';
$status 'error';
$redirectURL 'index.php';
if(isset(
$_POST['signupSubmit'])){
    
$redirectURL 'registration.php';
    
    
// Get user's input
    
$postData $_POST;
    
$first_name trim($_POST['first_name']);
    
$last_name trim($_POST['last_name']);
    
$email trim($_POST['email']);
    
$phone trim($_POST['phone']);
    
$password trim($_POST['password']);
    
$confirm_password trim($_POST['confirm_password']);
    
    
// Validate form fields
    
if(empty($first_name)){
        
$valErr .= 'Please enter your first name.<br/>';
    }
    if(empty(
$last_name)){
        
$valErr .= 'Please enter your last name.<br/>';
    }
    if(empty(
$email) || !filter_var($emailFILTER_VALIDATE_EMAIL)){
        
$valErr .= 'Please enter a valid email.<br/>';
    }
    if(empty(
$phone)){
        
$valErr .= 'Please enter your phone no.<br/>';
    }
    if(empty(
$password)){
        
$valErr .= 'Please enter login password.<br/>';
    }
    if(empty(
$confirm_password)){
        
$valErr .= 'Please confirm your password.<br/>';
    }
    if(
$password !== $confirm_password){
        
$valErr .= 'Confirm password should be matched with the password.<br/>';
    }
    
    
// Check whether user inputs are empty
    
if(empty($valErr)){
        
// Check whether the user already exists with the same email in the database
        
$prevCon['where'] = array(
            
'email'=>$_POST['email']
        );
        
$prevCon['return_type'] = 'count';
        
$prevUser $user->getRows($prevCon);
        if(
$prevUser 0){
            
$statusMsg 'Email already registered, please use another email.';
        }else{
            
// Insert user data in the database
            
$password_hash md5($password);
            
$userData = array(
                
'first_name' => $first_name,
                
'last_name' => $last_name,
                
'email' => $email,
                
'password' => $password_hash,
                
'phone' => $phone
            
);
            
$insert $user->insert($userData);
            
            if(
$insert){
                
$status 'success';
                
$statusMsg 'Your account has been registered successfully, login to the account.';
                
$postData '';
                
                
$redirectURL 'index.php';
            }else{
                
$statusMsg 'Something went wrong, please try again after some time.';
            }
        }
    }else{
        
$statusMsg '<p>Please fill all the mandatory fields:</p>'.trim($valErr'<br/>');
    }
    
    
// Store registration status into the SESSION
    
$sessData['postData'] = $postData;
    
$sessData['status']['type'] = $status;
    
$sessData['status']['msg'] = $statusMsg;
    
$_SESSION['sessData'] = $sessData;
    
    
// Redirect to the home/registration page
    
header("Location: $redirectURL");
}elseif(isset(
$_POST['loginSubmit'])){
    
// Get user's input
    
$postData $_POST;
    
$email trim($_POST['email']);
    
$password trim($_POST['password']);
    
    
// Validate form fields
    
if(empty($email) || !filter_var($emailFILTER_VALIDATE_EMAIL)){
        
$valErr .= 'Please enter a valid email.<br/>';
    }
    if(empty(
$password)){
        
$valErr .= 'Please enter your password.<br/>';
    }
    
    
// Check whether user inputs are empty
    
if(empty($valErr)){
        
// Check whether the user account exists with active status in the database
        
$password_hash md5($password);
        
$conditions['where'] = array(
            
'email' => $email,
            
'password' => $password_hash,
            
'status' => 1
        
);
        
$conditions['return_type'] = 'single';
        
$userData $user->getRows($conditions);
        
        if(!empty(
$userData)){
            
$status 'success';
            
$statusMsg 'Welcome '.$userData['first_name'].'!';
            
$postData '';
            
            
$sessData['userLoggedIn'] = TRUE;
            
$sessData['userID'] = $userData['id'];
        }else{
            
$statusMsg 'Wrong email or password, please try again!';
        }
    }else{
        
$statusMsg '<p>Please fill all the mandatory fields:</p>'.trim($valErr'<br/>');
    }
    
    
// Store login status into the SESSION
    
$sessData['postData'] = $postData;
    
$sessData['status']['type'] = $status;
    
$sessData['status']['msg'] = $statusMsg;
    
$_SESSION['sessData'] = $sessData;
    
    
// Redirect to the home page
    
header("Location: $redirectURL");
}elseif(!empty(
$_REQUEST['logoutSubmit'])){
    
// Remove session data
    
unset($_SESSION['sessData']);
    
session_destroy();
    
    
// Store logout status into the SESSION
    
$sessData['status']['type'] = 'success';
    
$sessData['status']['msg'] = 'You have logout successfully!';
    
$_SESSION['sessData'] = $sessData;
    
    
// Redirect to the home page
    
header("Location: $redirectURL");
}else{
    
// Redirect to the home page
    
header("Location: $redirectURL");
}

Registration Form (registration.php)

The following HTML form elements allow to input the account informations (name, email, password, etc.) for registration.

  • On submission, the form data is submitte to the server-side script (userAccount.php) to process the signup request.
<?php 
// Start session
session_start();

// Get data from session
$sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:'';

// Get status from session
if(!empty($sessData['status']['msg'])){
    
$statusMsg $sessData['status']['msg'];
    
$status $sessData['status']['type'];
    unset(
$_SESSION['sessData']['status']);
}

$postData = array();
if(!empty(
$sessData['postData'])){
    
$postData $sessData['postData'];
    unset(
$_SESSION['postData']);
}
?> <!-- Status message --> <?php if(!empty($statusMsg)){ ?> <div class="status-msg <?php echo $status?>"><?php echo $statusMsg?></div> <?php ?> <div class="regisFrm"> <form action="userAccount.php" method="post"> <input type="text" name="first_name" placeholder="FIRST NAME" value="<?php echo !empty($postData['first_name'])?$postData['first_name']:''?>" required=""> <input type="text" name="last_name" placeholder="LAST NAME" value="<?php echo !empty($postData['last_name'])?$postData['last_name']:''?>" required=""> <input type="email" name="email" placeholder="EMAIL" value="<?php echo !empty($postData['email'])?$postData['email']:''?>" required=""> <input type="text" name="phone" placeholder="PHONE NUMBER" value="<?php echo !empty($postData['phone'])?$postData['phone']:''?>" required=""> <input type="password" name="password" placeholder="PASSWORD" required=""> <input type="password" name="confirm_password" placeholder="CONFIRM PASSWORD" required=""> <div class="send-button"> <input type="submit" name="signupSubmit" value="CREATE ACCOUNT"> </div> </form> </div>

Login Form and User Account Details (index.php)

Initially, the login form is displayed to allow the user signin with email and password.

  • If the user logged-in already, account details section is displayed.
  • In the login screen, registration link is provided.
  • In the account screen, logout link is provided.
<?php 
// Start session
session_start();

// Get data from session
$sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:'';

// Get status from session
if(!empty($sessData['status']['msg'])){
    
$statusMsg $sessData['status']['msg'];
    
$status $sessData['status']['type'];
    unset(
$_SESSION['sessData']['status']);
}

$postData = array();
if(!empty(
$sessData['postData'])){
    
$postData $sessData['postData'];
    unset(
$_SESSION['postData']);
}

// If the user already logged in
if(!empty($sessData['userLoggedIn']) && !empty($sessData['userID'])){
    include_once 
'User.class.php';
    
$user = new User();
    
$conditions['where'] = array(
        
'id' => $sessData['userID']
    );
    
$conditions['return_type'] = 'single';
    
$userData $user->getRows($conditions);
}
?> <?php if(!empty($userData)){ ?> <h2>Welcome <?php echo $userData['first_name']; ?>!</h2> <a href="userAccount.php?logoutSubmit=1" class="logout">Logout</a> <div class="regisFrm"> <p><b>Name: </b><?php echo $userData['first_name'].' '.$userData['last_name']; ?></p> <p><b>Email: </b><?php echo $userData['email']; ?></p> <p><b>Phone: </b><?php echo $userData['phone']; ?></p> </div> <?php }else{ ?> <h2>Login to Your Account</h2> <!-- Status message --> <?php if(!empty($statusMsg)){ ?> <div class="status-msg <?php echo $status?>"><?php echo $statusMsg?></div> <?php ?> <div class="regisFrm"> <form action="userAccount.php" method="post"> <input type="email" name="email" placeholder="EMAIL" value="<?php echo !empty($postData['email'])?$postData['email']:''?>" required=""> <input type="password" name="password" placeholder="PASSWORD" required=""> <div class="send-button"> <input type="submit" name="loginSubmit" value="LOGIN"> </div> </form> <p>Don't have an account? <a href="registration.php">Register</a></p> </div> <?php ?>

PHP User Login System Script

Conclusion

Hope this step-by-step tutorial and example script help you to implement the registration and login system in the PHP web application. You can integrate user login functionality in the website with PHP and MySQL using SESSION. Also, you can extend the User Class to build an advanced user authentication system and user management system.
Next Part: Forgot Password Recovery Functionality Implementation in Login System with PHP and MySQL

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

28 Comments

  1. Eli Said...
  2. Tanjib Rubyat Said...
  3. Nathaniel Said...
  4. Vasman Said...
  5. Syed Ali Ahamad Said...
  6. Edwin Said...
  7. Ananth Said...
  8. Kilo Said...
  9. Quadryl Said...
    • CodexWorld Said...
  10. Narayana Said...
  11. Adam Said...
  12. Suhe Said...
  13. Abbi Said...
  14. Ryan Said...
  15. Rakim Said...
    • CodexWorld Said...
  16. Deepjyoti Baiahya Said...
  17. Kalai Said...
  18. Lawrence Igwegbe Said...
  19. Punith Said...
  20. Olli Said...
  21. Ion Vladescu Said...
  22. Shannu Said...
  23. Robin Tyagi Said...
  24. Tom Said...

Leave a reply

keyboard_double_arrow_up