Home > Backend Development > PHP Tutorial > PHP effectively prevents the same user from logging in multiple times_php tips

PHP effectively prevents the same user from logging in multiple times_php tips

WBOY
Release: 2016-05-16 20:04:26
Original
1172 people have browsed it

[Problem description]: It is dangerous if the same user logs in multiple times at the same time if it cannot be detected. 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") ; 
Copy after login

(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(); 
Copy after login

(3) Create a session to save the username

$_SESSION["username"] = $username; 
Copy after login

(4) Use url rewriting and pass session_id

$url = "main.php?sid=".session_id(); 
unset($db); 
echo "<font color=blue>登录成功,正在跳转!</font>" ; 
header ("Location:$url"); 
Copy after login

(5) Add
at the beginning of the page you want to jump to
main.php

<&#63;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 () ; 
} 
&#63;> 
 
<html> 
<body> 
...... 
</body> 
</html>
Copy after login

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.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template