Home > Article > Backend Development > Ensure unique user login using PHP
Title: Using PHP to ensure unique user login
In web development, ensuring the security of user accounts is a crucial task. Among them, ensuring that users can only log in on one device at a time is a common strategy. This article will introduce how to use PHP to write code to implement the function of ensuring that a unique user logs in.
First of all, we need a user login system, including a login page, code to verify login information, and how to store user information. The following is the HTML code for a simple user login page:
<!DOCTYPE html> <html> <head> <title>用户登录</title> </head> <body> <h2>用户登录</h2> <form action="login.php" method="post"> <label for="username">用户名:</label> <input type="text" id="username" name="username" required><br><br> <label for="password">密码:</label> <input type="password" id="password" name="password" required><br><br> <input type="submit" value="登录"> </form> </body> </html>
Next, we need to write the login.php file to verify the username and password entered by the user and implement the logic of unique user login. The following is a code example for login.php:
<?php session_start(); $users = [ 'user1' => 'password1', 'user2' => 'password2', // 其他用户信息 ]; $username = $_POST['username']; $password = $_POST['password']; if (array_key_exists($username, $users) && $users[$username] === $password) { if (isset($_SESSION['username']) && $_SESSION['username'] !== $username) { unset($_SESSION['username']); session_regenerate_id(); // 重新生成session_id } $_SESSION['username'] = $username; echo '登录成功,欢迎' . $username; } else { echo '用户名或密码错误'; } ?>
In the above code, we first create an associative array $users to store the user's username and password. When the user logs in, it will first determine whether the entered user name and password match the information in $users. If they match, the user name will be stored in $_SESSION and the login success information will be printed. The key step is to regenerate the session_id through the session_regenerate_id() function to prevent the old session from being continued to be used.
Finally, we also need to write a logout.php file for user logout operation:
<?php session_start(); unset($_SESSION['username']); session_destroy(); echo '您已成功注销'; ?>
The above is a simple example of using PHP to achieve unique user login. When a user logs in, the system will detect whether there are other users logged in. If so, it will log out and regenerate the session_id to ensure that only one user can log in. When the user logs out, the user name information in the session will be deleted and the session will be destroyed. This ensures that users can only log in on one device at a time.
The above is the detailed content of Ensure unique user login using PHP. For more information, please follow other related articles on the PHP Chinese website!