Wednesday 19 January 2022

How to Prevent Multiple Login for Same User in PHP

In this post, We have share tutorial on How to allow an User to be logged in from one location at a time, if User has try to login from other location then that User will be logout from his first login location. So this things we will learn under this tutorial by using PHP script with MySQL Database. By using this tutorial you can implement how to disable or prevent multiple logins for a user, that means User cannot be logged in from more location or more than one login session at a time.

By using this feature if User has been already login into system from one location or place and try to login into system by using same login credential at another place then that User first login will be logout immediately without giving any further notice.

Why we want to prevent multiple login to single user using same login details, this is because by using this block or prevent multiple login to single user for deter account sharing that means many person has been use single paid account.

So by using Prevent Multiple Login, We have make functionality like sharing of single account will be almost pointless this is because when single user is already login into system and elsewhere same user is try to login into system then first user current session will be automatically closed that means first login will be logout from the system. So by using this feature sharing of single user account will more difficult.


How to Prevent Multiple Login for Same User in PHP






Source


MySQL Table


For create functionality like Prevent Multiple Login of Single User at the same time, first we need to create user login table. For create table in MySQL databae you have to run following script in your phpMyAdmin.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `user_login`
--

CREATE TABLE `user_login` (
  `user_id` int(11) NOT NULL,
  `user_email` varchar(100) NOT NULL,
  `user_password` varchar(100) NOT NULL,
  `user_session_id` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `user_login`
--

INSERT INTO `user_login` (`user_id`, `user_email`, `user_password`, `user_session_id`) VALUES
(1, 'johnsmith@gmail.com', 'password', 'rped8169spskdor9ufd8kui084'),
(2, 'peterparker@gmail.com', 'password', '5gv1bxki');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `user_login`
--
ALTER TABLE `user_login`
  ADD PRIMARY KEY (`user_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `user_login`
--
ALTER TABLE `user_login`
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;


This script will create user_login table in your MySQL database and under this table login details has been saved in user_email and user_password table column, and in user_session_id table column, we will store current session id of User login. So when user has been login into system then new session id will be updated under this column and based on session id we will prevent multiple login of same user at a same time by using PHP script.





database_connection.php


This PHP file will be used for make MySQL Database connection by using PHP PDO Object.


<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");


?>


index.php


In this file we will make login form for get grant access into system. Under this file first we will make HTML Login form.

In this file we have also validate user login crentials also. But before validate User login data first it has been validate form data, if form data is proper then after it has been validate login data.

At the time of login data validation first it has check user email address details is proper then after it will check user has enter proper password, so if user has enter corrent email and correct password then after it will process for grant access into system.

So after validate User email and password details now give permission for access system, here we have to validate User login by store user id in $_SESSION variable, this is because from any web page we can access $_SESSION variable value. So for store data in $_SESSION variable, here we have to start session by using session_start() function and then after after we have to generate new session id by using session_regenerate_id() function and by using session_id() function we can get newly generated session id and lastly we have to update that session id value in user login table by using PHP script and lastly user will be redirect to home.php file.


<?php 

//index.php

include 'database_connection.php';

$message = '';

if(isset($_POST["login_button"]))
{
    $formdata = array();

    if(empty($_POST["user_email"]))
    {
        $message .= '<li>Email Address is required</li>';
    }
    else
    {
        if(!filter_var($_POST["user_email"], FILTER_VALIDATE_EMAIL))
        {
            $message .= '<li>Invalid Email Address</li>';
        }
        else
        {
            $formdata['user_email'] = $_POST['user_email'];
        }
    }

    if(empty($_POST['user_password']))
    {
        $message .= '<li>Password is required</li>';
    }
    else
    {
        $formdata['user_password'] = $_POST['user_password'];
    }

    if($message == '')
    {
        $data = array(
            ':user_email'       =>  $formdata['user_email']
        );

        $query = "
        SELECT * FROM user_login 
        WHERE user_email = :user_email
        ";

        $statement = $connect->prepare($query);

        $statement->execute($data);

        if($statement->rowCount() > 0)
        {
            foreach($statement->fetchAll() as $row)
            {
                if($row['user_password'] == $formdata['user_password'])
                {
                    session_start();

                    session_regenerate_id();

                    $user_session_id = session_id();

                    $query = "
                    UPDATE user_login 
                    SET user_session_id = '".$user_session_id."' 
                    WHERE user_id = '".$row['user_id']."'
                    ";

                    $connect->query($query);

                    $_SESSION['user_id'] = $row['user_id'];

                    $_SESSION['user_session_id'] = $user_session_id;

                    header('location:home.php');
                }
                else
                {
                    $message = '<li>Wrong Password</li>';
                }
            }
        }
        else
        {
            $message = '<li>Wrong Email Address</li>';
        }
    }
}

?>

<!doctype html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

        <title>How to stop Multiple Logins from the same user in PHP</title>
    </head>
    <body>

        <div class="container">
            <h1 class="mt-5 mb-5 text-center text-primary">How to stop Multiple Logins from the same user in PHP</h1>
            <div class="row">
                <div class="col-md-3">&nbsp;</div>
                <div class="col-md-6">
                    <?php 
                    if($message != '')
                    {
                        echo '<div class="alert alert-danger"><ul>'.$message.'</ul></div>';
                    }
                    ?>
                    <div class="card">
                        <div class="card-header">Login</div>
                        <div class="card-body">
                            <form method="POST">
                                <div class="mb-3">
                                    <label class="form-label">Email address</label>
                                    <input type="text" name="user_email" class="form-control" />
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Password</label>
                                    <input type="password" name="user_password" class="form-control" />
                                </div>
                                <div class="d-flex align-items-center justify-content-between mt-4 mb-0">
                                    <input type="submit" name="login_button" value="Login" class="btn btn-primary" />
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>




home.php


This file will be access by user only after login into system, if any user try to access this page without login into system then user will be redirect to login page.

On this web page login user can view logout link and user can also view their current session id value also.

Under this file we have also make one javascript check_session_id() function and this function has been send ajax request for compare user session id which we have store under $_SESSION variable with session id store under user_login table. If both session id value is not match then user will be automatically redirect to logout.php file and user will be logout from system and redirect to login page.


<?php 

//home.php

session_start();

if(!isset($_SESSION['user_session_id']))
{
    header('location:index.php');
}

?>

<!doctype html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

        <title>How to stop Multiple Logins from the same user in PHP</title>
    </head>
    <body>

        <div class="container">
            <h1 class="mt-5 mb-5 text-center text-primary">How to stop Multiple Logins from the same user in PHP</h1>
            
            <h2>Welcome User</h2>
            <p><a href="logout.php">Logout</a></p>
            <?php 
            echo '<pre>';
            print_r($_SESSION);
            echo '</pre>';
            ?>
        </div>
    </body>
</html>

<script>

function check_session_id()
{
    var session_id = "<?php echo $_SESSION['user_session_id']; ?>";

    fetch('check_login.php').then(function(response){

        return response.json();

    }).then(function(responseData){

        if(responseData.output == 'logout')
        {
            window.location.href = 'logout.php';
        }

    });
}

setInterval(function(){

    check_session_id();
    
}, 10000);

</script>


check_login.php


This file has been mainly received Ajax request for check session id which we have stored under $_SESSION variable has been match with session id which we have stored under MySQL table and based on comparison it has send response to Ajax request in json format by using json_encode() function.


<?php 

//check_login.php

include 'database_connection.php';

session_start();

$query = "
	SELECT user_session_id FROM user_login 
	WHERE user_id = '".$_SESSION['user_id']."'
";

$result = $connect->query($query);

foreach($result as $row)
{
	if($_SESSION['user_session_id'] != $row['user_session_id'])
	{
		$data['output'] = 'logout';
	}
	else
	{
		$data['output'] = 'login';
	}
}

echo json_encode($data);

?>


logout.php


This file has been used for removed all session variable and after this it will redirect user to login page. That means user will be logout from system using PHP script.


<?php 

//logout.php

session_id($_SESSION['user_session_id']);

session_start();

session_destroy();

header('location:index.php');


?>


So here we have step by step show you procedure for how to prevent multiple logins from same user in PHP script. So if you are looking for how to restrict multiple login using a single account in php then this tutorial will help you for implement multiple login by same user at same time using PHP.







2 comments: