Sometimes required to restrict the user to only log in on a single system or a browser at a time.
To prevent the user from login on multiple systems or web browsers you need to generate a token on each successful login attempt.
Need to check the token on each page. If the token does not match then destroy the SESSION and log out the user.
In this tutorial, I show how you can prevent multiple logins of the same user with PHP.
Contents
1. Table structure
I am using users and user_token table in the tutorial example.
users table –
CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(60) NOT NULL, `fullname` varchar(70) NOT NULL, `password` varchar(60) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
user_token table –
CREATE TABLE `user_token` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(80) NOT NULL, `token` varchar(80) NOT NULL, `timemodified` timestamp NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
2. Configuration
Create a config.php for database connection.
Completed Code
<?php
session_start();
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
3. HTML
Create a login form with two input elements and a submit button.
Completed Code
<div class="container">
<form method="post" action="">
<div id="div_login">
<h1>Login</h1>
<div>
<input type="text" class="textbox" id="txt_uname" name="txt_uname" placeholder="Username" required />
</div>
<div>
<input type="password" class="textbox" id="txt_pwd" name="txt_pwd" placeholder="Password" required />
</div>
<div>
<input type="submit" value="Submit" name="but_submit" id="but_submit" />
</div>
</div>
</form>
</div>
4. CSS
/* Container */
.container{
width:40%;
margin:0 auto;
}
/* Login */
#div_login{
border: 1px solid gray;
border-radius: 3px;
width: 470px;
height: 270px;
box-shadow: 0px 2px 2px 0px gray;
margin: 0 auto;
}
#div_login h1{
margin-top: 0px;
font-weight: normal;
padding: 10px;
background-color: cornflowerblue;
color: white;
font-family: sans-serif;
}
#div_login div{
clear: both;
margin-top: 10px;
padding: 5px;
}
#div_login .textbox{
width: 96%;
padding: 7px;
}
#div_login input[type=submit]{
padding: 7px;
width: 100px;
background-color: lightseagreen;
border: 0px;
color: white;
}
/* media */
@media screen and (max-width:720px){
.container{
width: 100%;
}
#div_login{
width: 99%;
}
}
5. PHP
Check login & generate a token
On <form> submit match username and password in the users table.
If a record is available then initialize a $_SESSION['username'] and generate a token value to initialize $_SESSION['token'] variable.
Check user record already exist or not in the user_token table if it exists then update the token field value otherwise insert a new record.
Redirect to home.php file.
Completed Code
<?php
include "config.php";
if(isset($_POST['but_submit'])){
$uname = mysqli_real_escape_string($con,$_POST['txt_uname']);
$password = mysqli_real_escape_string($con,$_POST['txt_pwd']);
if ($uname != "" && $password != ""){
$sql_query = "select count(*) as cntUser from users where username='".$uname."' and password='".$password."'";
$result = mysqli_query($con,$sql_query);
$row = mysqli_fetch_array($result);
$count = $row['cntUser'];
if($count > 0){
$token = getToken(10);
$_SESSION['username'] = $uname;
$_SESSION['token'] = $token;
// Update user token
$result_token = mysqli_query($con, "select count(*) as allcount from user_token where username='".$uname."' ");
$row_token = mysqli_fetch_assoc($result_token);
if($row_token['allcount'] > 0){
mysqli_query($con,"update user_token set token='".$token."' where username='".$uname."'");
}else{
mysqli_query($con,"insert into user_token(username,token) values('".$uname."','".$token."')");
}
header('Location: home.php');
}else{
echo "Invalid username and password";
}
}
}
// Generate token
function getToken($length){
$token = "";
$codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
$codeAlphabet.= "0123456789";
$max = strlen($codeAlphabet); // edited
for ($i=0; $i < $length; $i++) {
$token .= $codeAlphabet[random_int(0, $max-1)];
}
return $token;
}
Check token
Create a new check_token.php file to check the user token on the required pages.
If the user $_SESSION['token']does not match the value stored in user_token table means the user is logged in on some other browser or system.
Destroy the SESSION and redirect it to the index.php file.
Completed Code
<?php
if (isset($_SESSION['username'])) {
$result = mysqli_query($con, "SELECT token FROM user_token where username='".$_SESSION['username']."'");
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
$token = $row['token'];
if($_SESSION['token'] != $token){
session_destroy();
header('Location: index.php');
}
}
}
Homepage
Create a new home.php file. This file will show after successful login. Include above created check_token.php file after config.php.
If $_SESSION['username'] is not set then redirect to index.php file.
Created an anchor element for logout.
Completed Code
<?php
include "config.php";
include "check_token.php"; // Check user token
// Check user login or not
if(!isset($_SESSION['username'])){
header('Location: index.php');
}
?>
<!doctype html>
<html>
<head></head>
<body>
<h1>Homepage</h1>
<br>
<a href="logout.php">Logout</a>
</body>
</html>
Logout
Create a logout.php file for deleting SESSION and user token.
Check if $_SESSION['username'] is set or not. If set then delete a record from the user_token table by username and destroy the SESSION.
Redirect to index.php file.
Completed Code
<?php
include "config.php";
if(isset($_SESSION['username'])){
// Delete token
$uname = mysqli_real_escape_string($con,$_SESSION['username']);
mysqli_query($con, "delete from user_token where username = '".$uname."'");
// Destroy session
session_destroy();
header('Location: index.php');
}else{
header('Location: index.php');
}
6. Conclusion
Using the above PHP script you can prevent the multiple logins of the user and automatically log out from other places when it gets logged in.
If you found this tutorial helpful then don't forget to share.

Nice post and very usefull!
rik
Thank you for this, I modified it a bit to work with my CakePHP app but it works great. Now to decide whether it’s
im sorry. im new to this PHP.
may i know. do i have to create users table in the tutorial database? im copying exactly your codes but it shows invalid username.
Thank you, master! Sensational! Grettings from Brazil!
Sir actually i’ve created a my_database inside that one user table may i know where i will create a user_token table?
this demo project is not working
Thanks, Yogesh! Seems you are reading my mind 🙂 I needed this just now! I was stuck somewhere in the “Table Structure & Configuration side “, and your code helped me.
Keep sharing nice stuff like this.
Hey Yogesh. Great piece of work.
So, this basically makes a new request(page refresh) to check the token and destroy the session if token is different.
I’m stuck in a different use case. where if the second user logs in, the first user should be automatically forced to logout. without any new request(page refresh).
Any insights on this ?
Fatal error: Call to undefined function random_int() in C:\xampp\htdocs\ron\index.php on line 124 how can i resolve this
So we need to delete the token after we log-out to allow login another day right or another time at the same day
But what if we never click logout, just close the browser or suddenly the power down and the pc suddenly off ? we cant login because the last token still there, isn’t it ?
can u share me the codes all on sanjay6681@gmail.com
Hello, You have tutorial like for codeigniter 2 ?
thanx for the great tutorial, one thing i think would make it a bit easyer
it’s about generating the tokens in one line instead of long function
$token = md5(microtime().rand()); //to generate activation token
why it is not redirecting anymore after the row was created in the token table?
Thank you so much, it’s work
how this implementation will be done using java
if the some other person gets logged in, how can i detect the location,time and date of that person?
if the some other person gets logged in, how can i detect the location,time and date of that person?
Great article. How can I implement following scenario:
1. Let’s say user A logs in first on one browser.
2. User B tries to log in using the same login and password on a different browser.
3. User B get’s message “someone is already logged in, please loggout on your other device to gain access.”
I want to avoid situation when user A gets automatically logged out once user B uses the same login and pass.
Thanks!
i also have the same question… i prefer if possible when new attempt of log in is tried, the message will be ” you are currently logged on ” but we also need it to auto log out automatically when user is closing the browser or inactive for certain period of time or disconnected
how to implement multiple user login system in php
Thanks Yogesh! It’s really helpful. And also it can help to prevent Session Hijacking, right??
how to implement with social login(fb,google), classical user+pass login with different table?
Hi this is useful information but you have to prevent back button after login and accessing the login page after login.How to do it please comment
Hello sir very useful when we are login in second broweser it opens the page when we refresh only it signs out
But i need something like then the same user id and pass is used on the second broweser it should say you can login only in 1 brower like that please please please help
Thank you, sir, for its very helpful
will you please share me code like
how to prevent the user to open the same URL in multiple tabs in the same browser in PHP
I am trying to login using 2 different browsers, still I can login on both at same time. Only on first browser after refreshing it shows as logge out. I need a code that should tell the user at the time of login itself that other session is already in use.
Hi Akash,
Did you find any solution for this.
do you have any video tutorial on this, on which you are making this happening, or any video which you can suggest me.
Hi Yogesh,
Can we achieve this using javascript.?
If yes could you help me in generating and validating the token using javascript..
Thanks in advance,
Mounika Bora
Hi Sir I am using this now,
Do you have a registration page of this?
Can you email the code to me please.
Thanks in Advance.
Happy New Year.