Registration and Login System with PHP and MySQL


Login system is a key feature for every membership website. Registration and login system implementation is very easy with PHP. In this tutorial, we’ll show you how to build a simple login system with PHP and MySQL.

Our PHP script will demonstrate the user registration and login system with MySQL and PHP Session. Also, PHP server side validation is used on login and registration to validate user data.

Before you begin take a look at the used files and their uses in PHP Login System.

  • user.php – handle database related works
  • userAccount.php – handle registration, login, and logout request with User Class
  • index.php – display login form / user details
  • registration.php – display registration form
  • style.css – styling login and registration form

Database Table Creation

A table is needed to store the user details in the database. The following SQL creates a users table with some required columns.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `first_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `last_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(100) 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` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

User Class (user.php)

User Class handles all the database related works, it contains 3 methods, __construct(), getRows(), and insert(). __construct() function is used to connect the database, getRows() function is used to fetch the user data from the database, and insert() function inserts the user details to the database. In this file, you need to change $dbHost, $dbUsername, $dbPassword, $dbName variables value with your MySQL database credentials.

<?php
/*
 * User Class
 * This class is used for database related (connect, fetch, and insert) operations
 * @author    CodexWorld.com
 * @url       http://www.codexworld.com
 * @license   http://www.codexworld.com/license
 */
class User{
    private 
$dbHost     "localhost";
    private 
$dbUsername "root";
    private 
$dbPassword "";
    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;
        }
    }
}

userAccount.php

This file controls the registration, login, and logout request which comes from index.php and registration.php. The User Class is used to get and insert user details to the users table. Also, PHP Sessions are used to hold the login status of the user.

<?php
//start session
session_start();
//load and initialize user class
include 'user.php';
$user = new User();
if(isset(
$_POST['signupSubmit'])){
    
//check whether user details are empty
    
if(!empty($_POST['first_name']) && !empty($_POST['last_name']) && !empty($_POST['email']) && !empty($_POST['phone']) && !empty($_POST['password']) && !empty($_POST['confirm_password'])){
        
//password and confirm password comparison
        
if($_POST['password'] !== $_POST['confirm_password']){
            
$sessData['status']['type'] = 'error';
            
$sessData['status']['msg'] = 'Confirm password must match with the password.'
        }else{
            
//check whether user exists in the database
            
$prevCon['where'] = array('email'=>$_POST['email']);
            
$prevCon['return_type'] = 'count';
            
$prevUser $user->getRows($prevCon);
            if(
$prevUser 0){
                
$sessData['status']['type'] = 'error';
                
$sessData['status']['msg'] = 'Email already exists, please use another email.';
            }else{
                
//insert user data in the database
                
$userData = array(
                    
'first_name' => $_POST['first_name'],
                    
'last_name' => $_POST['last_name'],
                    
'email' => $_POST['email'],
                    
'password' => md5($_POST['password']),
                    
'phone' => $_POST['phone']
                );
                
$insert $user->insert($userData);
                
//set status based on data insert
                
if($insert){
                    
$sessData['status']['type'] = 'success';
                    
$sessData['status']['msg'] = 'You have registered successfully, log in with your credentials.';
                }else{
                    
$sessData['status']['type'] = 'error';
                    
$sessData['status']['msg'] = 'Some problem occurred, please try again.';
                }
            }
        }
    }else{
        
$sessData['status']['type'] = 'error';
        
$sessData['status']['msg'] = 'All fields are mandatory, please fill all the fields.'
    }
    
//store signup status into the session
    
$_SESSION['sessData'] = $sessData;
    
$redirectURL = ($sessData['status']['type'] == 'success')?'index.php':'registration.php';
    
//redirect to the home/registration page
    
header("Location:".$redirectURL);
}elseif(isset(
$_POST['loginSubmit'])){
    
//check whether login details are empty
    
if(!empty($_POST['email']) && !empty($_POST['password'])){
    
//get user data from user class
        
$conditions['where'] = array(
            
'email' => $_POST['email'],
            
'password' => md5($_POST['password']),
            
'status' => '1'
        
);
        
$conditions['return_type'] = 'single';
        
$userData $user->getRows($conditions);
        
//set user data and status based on login credentials
        
if($userData){
            
$sessData['userLoggedIn'] = TRUE;
            
$sessData['userID'] = $userData['id'];
            
$sessData['status']['type'] = 'success';
            
$sessData['status']['msg'] = 'Welcome '.$userData['first_name'].'!';
        }else{
            
$sessData['status']['type'] = 'error';
            
$sessData['status']['msg'] = 'Wrong email or password, please try again.'
        }
    }else{
        
$sessData['status']['type'] = 'error';
        
$sessData['status']['msg'] = 'Enter email and password.'
    }
    
//store login status into the session
    
$_SESSION['sessData'] = $sessData;
    
//redirect to the home page
    
header("Location:index.php");
}elseif(!empty(
$_REQUEST['logoutSubmit'])){
    
//remove session data
    
unset($_SESSION['sessData']);
    
session_destroy();
    
//store logout status into the ession
    
$sessData['status']['type'] = 'success';
    
$sessData['status']['msg'] = 'You have logout successfully from your account.';
    
$_SESSION['sessData'] = $sessData;
    
//redirect to the home page
    
header("Location:index.php");
}else{
    
//redirect to the home page
    
header("Location:index.php");
}

Login Form and User Account Details (index.php)

Initially index.php file is loaded with login form and registration page link. After login, the user ID is available in session and the respective user details are shown using the User class. Also, a logout link will appear if the user already logged in.

<?php
session_start
();
$sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:'';
if(!empty(
$sessData['status']['msg'])){
    
$statusMsg $sessData['status']['msg'];
    
$statusMsgType $sessData['status']['type'];
    unset(
$_SESSION['sessData']['status']);
}
?> <div class="container">     <?php
        
if(!empty($sessData['userLoggedIn']) && !empty($sessData['userID'])){
            include 
'user.php';
            
$user = new User();
            
$conditions['where'] = array(
                
'id' => $sessData['userID'],
            );
            
$conditions['return_type'] = 'single';
            
$userData $user->getRows($conditions);
    
?> <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> <?php echo !empty($statusMsg)?'<p class="'.$statusMsgType.'">'.$statusMsg.'</p>':''?> <div class="regisFrm"> <form action="userAccount.php" method="post"> <input type="email" name="email" placeholder="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 ?> </div>

Registration Form (registration.php)

This file contains registration form HTML and the form is submitted to the userAccount.php file with a signup request.

<?php
session_start
();
$sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:'';
if(!empty(
$sessData['status']['msg'])){
    
$statusMsg $sessData['status']['msg'];
    
$statusMsgType $sessData['status']['type'];
    unset(
$_SESSION['sessData']['status']);
}
?> <div class="container"> <h2>Create a New Account</h2>     <?php echo !empty($statusMsg)?'<p class="'.$statusMsgType.'">'.$statusMsg.'</p>':''?> <div class="regisFrm"> <form action="userAccount.php" method="post"> <input type="text" name="first_name" placeholder="FIRST NAME" required=""> <input type="text" name="last_name" placeholder="LAST NAME" required=""> <input type="email" name="email" placeholder="EMAIL" required=""> <input type="text" name="phone" placeholder="PHONE NUMBER" 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> </div>

CSS Code

The following CSS is used to styling the login and registration form.

.container {
    width: 40%;
    margin: 0 auto;
    background-color: #f7f7f7;
    color: #757575;
    font-family: 'Raleway', sans-serif;
    text-align: left;
    padding: 30px;
}
h2 {
    font-size: 30px;
    font-weight: 600;
    margin-bottom: 10px;
}
.container p {
    font-size: 18px;
    font-weight: 500;
    margin-bottom: 20px;
}
.regisFrm input[type="text"], .regisFrm input[type="email"], .regisFrm input[type="password"] {
    width: 94.5%;
    padding: 10px;
    margin: 10px 0;
    outline: none;
    color: #000;
    font-weight: 500;
    font-family: 'Roboto', sans-serif;
}
.send-button {
    text-align: center;
    margin-top: 20px;
}
.send-button input[type="submit"] {
    padding: 10px 0;
    width: 60%;
    font-family: 'Roboto', sans-serif;
    font-size: 18px;
    font-weight: 500;
    border: none;
    outline: none;
    color: #FFF;
    background-color: #2196F3;
    cursor: pointer;
}
.send-button input[type="submit"]:hover {
    background-color: #055d54;
}
a.logout{float: right;}
p.success{color:#34A853;}
p.error{color:#EA4335;}

Conclusion

We hope our step-by-step guide and example script will help to implement login system in PHP. Using our script, you’ll be able to integrate login system with PHP and MySQL in less time. Also, you can extend the User Class to build an advanced user authentication system and user management system.

Leave a reply

Connect With CodexWorld