Login and Registration Form in PHP MySQL with Session

By Ved Prakash N | Nov 04, 2023 | PHP
Share :

https://www.fundaofwebit.com/post/login-and-registration-form-in-php-mysql-with-session

How to create a Registration and Login System with PHP and MySQL.


In this tutorial, we walk through the complete process of creating a user registration system. Users can create an account by providing name, phone, email, and password. Form validation, Show success message, Email already exists/registered is done while user registration. Once the user registered, the user can login. User Login is done via email and password. Once logged in user redirect to dashboard. User can the Logout.

Pages are designed using Bootstrap CSS.

How to create a Registration and Login System with PHP and MySQL

Here are simple steps you have to follow to create a login and registration system in php.

1. Create a Database and Database Table
2. Connect to the Database
3. Create a Registration Form
4. Create a Login Form
5. Create a Home Page (index.php)
6. Create an Authentication Page for checking user is logged in or not.
7. Create a Dashboard Page so only logged-in users can access the dashboard page.
8. Logout user.


Step 1: Create a users Table in your Database

CREATE TABLE IF NOT EXISTS `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(50) NOT NULL,
 `phone` varchar(20) NOT NULL,
 `email` varchar(50) NOT NULL,
 `password` varchar(50) NOT NULL,
 PRIMARY KEY (`id`)
);


Step 2: Database Connection
Create a dbcon.php file  and paste the below code for database connectivity

<?php

$conn = mysqli_connect("localhost","root","","phptutorials");

if(!$conn){
    die("Connection Failed". mysqli_connect_error());
}

?>


Step 3: Register Form
Create a register.php file for user registration and paste the below code: 

<?php
session_start();
if(isset($_SESSION['loggedInStatus'])){
    header('Location: index.php');
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register Form in php mysql with session</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" >
 
</head>
<body>

    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-6">

                <div class="mt-4 card card-body shadow">

                    <h4>Register</h4>
                    <hr>
                    <?php
                    if(isset($_SESSION['errors']) && count($_SESSION['errors']) > 0){
                        foreach($_SESSION['errors'] as $error){
                            ?>
                            <div class="alert alert-warning"><?= $error; ?></div>
                            <?php
                        }
                        unset($_SESSION['errors']);
                    }

                    if(isset($_SESSION['message'])){
                        echo '<div class="alert alert-success">'.$_SESSION['message'].'</div>';
                        unset($_SESSION['message']);
                    }
                    ?>

                    <form action="register-code.php" method="POST">

                        <div class="mb-3">
                            <label>Name</label>
                            <input type="text" name="name" class="form-control" />
                        </div>
                        <div class="mb-3">
                            <label>Phone</label>
                            <input type="number" name="phone" class="form-control" />
                        </div>
                        <div class="mb-3">
                            <label>Email</label>
                            <input type="email" name="email" class="form-control" />
                        </div>
                        <div class="mb-3">
                            <label>Password</label>
                            <input type="password" name="password" class="form-control" />
                        </div>
                        <div class="mb-3">
                            <button type="submit" name="registerBtn" class="btn btn-primary w-100">Submit</button>
                        </div>
                        <div class="text-center">
                            <a href="login.php">Click here to Login</a>
                        </div>

                    </form>
                </div>

            </div>
        </div>
    </div>
   

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>


Create register-code.php file : So, now when you submit the register form, it goes to the form action attribute which redirects to register-code.php file and do the registration process so, to achieve it paste the below code:

<?php
session_start();

require_once "dbcon.php";

if(isset($_POST['registerBtn']))
{
    $name = mysqli_real_escape_string($conn,$_POST['name']);
    $phone = mysqli_real_escape_string($conn,$_POST['phone']);
    $email = mysqli_real_escape_string($conn,$_POST['email']);
    $password = mysqli_real_escape_string($conn,$_POST['password']);

    $errors = [];

    if($name == '' OR $phone == '' OR $email == '' OR $password == ''){
        array_push($errors, "All fields are required");
    }

    if($email != '' && !filter_var($email, FILTER_VALIDATE_EMAIL)){
        array_push($errors, "Enter valid email address");
    }

    if($email != ''){
        $userCheck = mysqli_query($conn, "SELECT email FROM users WHERE email='$email'");
        if($userCheck){
            if(mysqli_num_rows($userCheck) > 0){
                array_push($errors, "Email already registered");
            }
        }else{
            array_push($errors, "Something Went Wrong!");
        }
    }

    if(count($errors) > 0){
        $_SESSION['errors'] = $errors;
        header('Location: register.php');
        exit();
    }

    $query = "INSERT INTO users (name,phone,email,password) VALUES ('$name','$phone','$email','$password')";
    $userResult = mysqli_query($conn, $query);

    if($userResult){
        $_SESSION['message'] = "Registered Successfully";
        header('Location: index.php');
        exit();
    }else{
        $_SESSION['message'] = "Something Went Wrong";
        header('Location: register.php');
        exit();
    }

}

?>


Step 4: Login Form

Create a login.php file and paste the below code:

<?php
session_start();

if(isset($_SESSION['loggedInStatus'])){
    header('Location: index.php');
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login Form in php mysql with session</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="mt-4 card card-body shadow">

                    <h4>Login</h4>
                    <hr>

                    <?php
                    if(isset($_SESSION['errors']) && count($_SESSION['errors']) > 0){
                        foreach($_SESSION['errors'] as $error){
                            ?>
                            <div class="alert alert-warning"><?= $error; ?></div>
                            <?php
                        }
                        unset($_SESSION['errors']);
                    }

                    if(isset($_SESSION['message'])){
                        echo '<div class="alert alert-success">'.$_SESSION['message'].'</div>';
                        unset($_SESSION['message']);
                    }
                    ?>

                    <form action="login-code.php" method="POST">

                        <div class="mb-3">
                            <label>Email Id</label>
                            <input type="email" name="email" class="form-control" />
                        </div>
                        <div class="mb-3">
                            <label>Password</label>
                            <input type="password" name="password" class="form-control" />
                        </div>
                        <div class="mb-3">
                            <button type="submit" name="loginBtn" class="btn btn-primary w-100">Login Now</button>
                        </div>
                        <div class="text-center">
                            <a href="index.php">Go to Home Page</a>
                            <br/>
                            <br/>
                            <a href="register.php">Click here to Register</a>
                        </div>

                    </form>
                   
                </div>
            </div>
        </div>
    </div>
   

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>


Create login-code.php file : So, now when you submit the login form, it goes to the form action attribute which redirects to login-code.php file and do the login process so, to achieve it paste the below code:

<?php
session_start();

require_once 'dbcon.php';

if(isset($_POST['loginBtn']))
{
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $password = mysqli_real_escape_string($conn, $_POST['password']);

    $errors = [];

    if($email == '' OR $password == ''){
        array_push($errors, "All fields are mandetory");
    }

    if($email != '' && !filter_var($email, FILTER_VALIDATE_EMAIL)){
        array_push($errors, "Email is not valid");
    }
   
    if(count($errors) > 0)
    {
        $_SESSION['errors'] = $errors;
        header('Location: login.php');
        exit();
    }

    $userQuery = "SELECT * FROM users WHERE email='$email' AND password='$password'";
    $result = mysqli_query($conn, $userQuery);

    if($result){
        if(mysqli_num_rows($result) == 1){

            $_SESSION['loggedInStatus'] = true;
            $_SESSION['message'] = "Logged In Successfully!";
           
            header('Location: dashboard.php');
            exit();
           
        }else{

            array_push($errors, "Invalid Email or Password!");
            $_SESSION['errors'] = $errors;

            header('Location: login.php');
            exit();
        }
    }else{
        array_push($errors, "Something Went Wrong!");
        $_SESSION['errors'] = $errors;

        header('Location: login.php');
        exit();
    }

}
?>


Step 5: Create a index.php file (Home Page) and paste the below code

<?php session_start(); ?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login and Registration Form in PHP MySQL with Session</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

    <div class="container mt-4">
        <div class="card card-body shadow">

            <?php
                if(isset($_SESSION['message'])){
                    echo '<div class="alert alert-success">'.$_SESSION['message'].'</div>';
                    unset($_SESSION['message']);
                }
            ?>

            <div class="row">
                <div class="col-md-12 text-center">

                    <h4>Login and Registration Form in PHP MySQL with Session</h4>
                    <br/>

                    <?php if(isset($_SESSION['loggedInStatus'])) : ?>

                        <a href="dashboard.php" class="btn btn-secondary">Dashboard</a>
                        <a href="logout.php" class="btn btn-danger">Logout</a>

                    <?php else: ?>

                        <a href="login.php" class="btn btn-primary">Login</a>
                        <a href="register.php" class="btn btn-info">Register</a>

                    <?php endif; ?>

                </div>
            </div>
           
        </div>
    </div>
   
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>


Step 6: Create a authentication.php for checking the user is logged in or not logged in. Paste below code

<?php
session_start();

if(!isset($_SESSION['loggedInStatus'])){

    $_SESSION['message'] = "Login to continue...";
   
    header('Location: login.php');
    exit();
}
?>


Step 7: Create a dashboard.php file, where in this dashboard only logged in user can access this page by including authentication.php file in it as follows:

<?php
include('authentication.php');
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
 
</head>
<body>

    <div class="container">
        <div class="mt-4 card card-body shadow">
            <h4>Welcome to Dashboard</h4>
            <?php
                if(isset($_SESSION['message'])){
                    echo '<div class="alert alert-success">'.$_SESSION['message'].'</div>';
                    unset($_SESSION['message']);
                }
            ?>
            <div>
                <a href="index.php" class="btn btn-primary">Home Page</a>
                <a href="logout.php" class="btn btn-danger">Logout</a>
            </div>
        </div>
    </div>
   

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>


Step 8: Create a logout.php file for logging out the user (Session Destroy) . Paste the below code

<?php
session_start();

session_destroy();
header('Location: login.php');
exit();

?>


Hope it helps you. Thanks for reading.

https://www.fundaofwebit.com/post/login-and-registration-form-in-php-mysql-with-session

Share this blog on social platforms