How To Make Php Login System Mysql Session

How To Make Php Login System Mysql Session

How To Make Php Login System Mysql Session

0 Sales

Free

For each membership portal, the authentication process is a key feature. Implementation of the registration and login system with PHP is very simple. In this tutorial, we're going to show you how to create a simple PHP and MySQL login system.

 

Our PHP script will demonstrate MySQL and PHP Session user registration and login system. PHP server side authentication is also used to verify user data while signing in and registering.

 

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

 

  • User.php–handle works related to the database user

  • Account.php–handle registration, login and login request with User Class index.

  • php–display registration form / user details.

  • php –display registration form style.

  • css–login styling and registration form.

 

Database Table Creation

To store the user details in the database, a table is required. The following SQL creates a table of users with some columns required.

 

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 performs all work related to the database, it includes three methods,   construct(), getRows(), and insert(). The function   construct() binds the database, the function getRows() extracts user information from the database, and the function insert() integrates user details into the database. In this file, with your MySQL database credentials, you need to change the value of $dbHost, $dbUsername, $dbPassword, $dbName variables.


 

<?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 directory manages the application from index.php and registration.php for server, login, and logout. User Class is used to get user details and add them into the table of users. PHP Sessions are also used to maintain the user's login status.

 

<?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)

 

The index.php file is initially loaded with the login form and the link to the registration page. The user ID will be available in session after login and the user details will be displayed using the user class. If the user has already logged in, a logout link will also appear.

 

<?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 HTML registration form and is submitted with a signup request to the userAccount.php file.

 

<?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;}


 

LICENSE OF USE

You can use it for personal or commercial projects. You can't resell it partially or in this form.

PRODUCT INFO

Create Date : May 14, 2020

Updated Date : May 14, 2020

Ratings

Comments : 0

Downloads : 0