Home > Article > Backend Development > php effectively prevents the same user from logging in multiple times, php effectively prevents login_PHP tutorial
[Problem description]: If the same user logs in multiple times at the same time, it cannot be detected It's dangerous to come out. Because, you have no way of knowing if other users are logging into your account. How to prevent the same user from logging in multiple times?
【Solution】
(1) Each time you log in and the identity authentication is successful, a session_id will be regenerated.
session_regenerate_id(); session_register ("username") ;
(2) Open a sessionid field in the user database, and update this field after regenerating session_id.
$sessionid = session_id(); $db = new PDO('sqlite:softToken.db'); $sql = "update userinfo set sessionid ='$sessionid' where username='$username' and passwd='$passwd';"; $query = $db->prepare($sql); $query->execute();
(3) Create a session to save the username
$_SESSION["username"] = $username;
(4) Use url rewriting and pass session_id
$url = "main.php?sid=".session_id(); unset($db); echo "<font color=blue>登录成功,正在跳转!</font>" ; header ("Location:$url");
(5) Add
at the beginning of the page you want to jump to
main.php
<?php header('Content-type:text/html; charset=utf-8'); $sessionid = $_GET['sid']; session_id($sessionid); session_start (); $username = $_SESSION["username"]; $db = new PDO('sqlite:softToken.db'); $sql = "select * from userinfo where username='$username' and sessionid='$sessionid';"; $query = $db->prepare($sql); $query->execute(); $user = $query->fetch(PDO::FETCH_OBJ); if ($user->username == ""){ session_destroy(); echo "<script language='javascript' type='text/javascript'>" ; echo "window.location.href = 'index.html';" ; echo "</script>" ; exit () ; } ?> <html> <body> ...... </body> </html>
The above is PHP’s solution to effectively prevent multiple logins to the same account at the same time. I hope it will be helpful to everyone in solving the problem of multiple logins to the same account at the same time.