Backend Development 8 min read

Implementing a Browser Login Limit with PHP

This article explains how to restrict the number of concurrent browser logins for a user account by storing login details in a database or Redis, comparing browser agent strings, and returning appropriate error messages, with full PHP code examples.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Implementing a Browser Login Limit with PHP

In traditional website development, user accounts and passwords are the basic authentication method, but allowing concurrent logins from multiple browsers or devices can pose security risks; without restrictions, an account may become a source of malicious activity.

This guide shows how to use PHP to limit the number of browsers a single account can be logged into simultaneously by recording login information, checking it on each login attempt, and denying access when the limit is exceeded.

Implementation Idea

1. Store user login information (user ID, session ID, browser agent string, login time) in a database or Redis. 2. When a login attempt occurs, read the stored information. 3. Compare the current browser's HTTP_USER_AGENT with the stored agent strings. 4. If the number of distinct browsers exceeds the configured limit, return an error; otherwise allow the login.

Database Table Structure

<code>CREATE TABLE `login_status` (
  `userid` int(11) NOT NULL COMMENT '用户ID',
  `session_id` varchar(50) NOT NULL COMMENT '会话ID',
  `browser_agent` varchar(100) DEFAULT NULL COMMENT '浏览器代理字符串',
  `login_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '登录时间'
);</code>

Store Login Information

<code>function saveLoginStatus($userid, $session_id, $browser_agent) {
    $db = new mysqli("localhost", "username", "password", "database");
    if ($db->connect_errno) {
        die("Failed to connect to MySQL: " . $db->connect_error);
    }
    $sql = "INSERT INTO login_status (userid, session_id, browser_agent) VALUES ('$userid', '$session_id', '$browser_agent')";
    if ($db->query($sql) === TRUE) {
        $db->close();
        return true;
    } else {
        $db->close();
        return false;
    }
}</code>

Read Login Information

<code>function getLoginStatus($userid) {
    $db = new mysqli("localhost", "username", "password", "database");
    if ($db->connect_errno) {
        die("Failed to connect to MySQL: " . $db->connect_error);
    }
    $sql = "SELECT * FROM login_status WHERE userid='$userid' ORDER BY login_time DESC";
    $result = $db->query($sql);
    $db->close();
    return $result->fetch_assoc();
}</code>

Compare Browser Agent Strings

<code>function compareBrowserAgent($agent1, $agent2) {
    return ($agent1 == $agent2);
}</code>

Return Error Information

<code>function sendError($message) {
    header("HTTP/1.1 403 Forbidden");
    header("Content-Type: application/json;charset=utf-8");
    die(json_encode(array(
        "code" => "403",
        "message" => $message
    )));
}</code>

Complete Example

<code>&lt;?php
function saveLoginStatus($userid, $session_id, $browser_agent) { /* ... */ }
function getLoginStatus($userid) { /* ... */ }
function compareBrowserAgent($agent1, $agent2) { /* ... */ }
function sendError($message) { /* ... */ }

$userid = $_POST["userid"];
$session_id = $_POST["session_id"];
$browser_agent = $_SERVER["HTTP_USER_AGENT"];
$limit = 5; // maximum allowed browsers
$status = getLoginStatus($userid);
if ($status == null) {
    saveLoginStatus($userid, $session_id, $browser_agent);
    die("登录成功!");
} else {
    $number_of_browsers = 1;
    if (compareBrowserAgent($browser_agent, $status["browser_agent"]) == false) {
        sendError("您已在其他浏览器中登录。");
    } else {
        $number_of_browsers = $number_of_browsers + 1;
    }
    while ($status = $result->fetch_assoc()) {
        if (compareBrowserAgent($browser_agent, $status["browser_agent"])) {
            $number_of_browsers = $number_of_browsers + 1;
        }
    }
    if ($number_of_browsers > $limit) {
        sendError("您已达到了浏览器登录数量的限制。");
    } else {
        saveLoginStatus($userid, $session_id, $browser_agent);
        die("登录成功!");
    }
}
?&gt;</code>

The code compares the current request's browser agent with previously stored agents; if the count of distinct browsers exceeds the limit, it returns a 403 error; otherwise, the login succeeds, helping developers protect accounts from malicious multi‑browser usage.

Conclusion

By storing login records and checking browser agent strings, developers can effectively limit the number of concurrent browser sessions per account, enhancing account security and preventing abuse.

BackendDatabasesecuritylogin
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.