You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP MySQL多级用户登录问题排查:用户越权访问后台及Session异常

Hey there! Let's break down the issues in your code that's causing the permission bypass and session anomalies. I'll go through each problem step by step, then share a fixed version of your code.

1. SQL Query Syntax Error

Your WHERE clause uses a comma instead of AND to separate conditions, which throws a MySQL syntax error. This means your query isn't returning any valid user data at all.

Original problematic line:

$query = "SELECT * FROM users_detail WHERE account = '$account',username= '$username' and password= '$password' ";

2. Not Fetching Actual User Data

You're only getting the count of rows with mysqli_num_rows($result), but never pulling the actual user record from the result set. When you try to access $rows['username'], you're trying to read an array key from an integer—this is invalid and triggers undefined index warnings.

3. Using Assignment Instead of Comparison in Checks

In your if statements, you're using = (assignment operator) instead of ==/=== (comparison operators). For example, $rows['username'] = $username will always evaluate to true because it's assigning a value, so your login validation is effectively bypassed entirely.

4. Flawed Logic Flow

Your two separate if statements mean the else only applies to the second check, not both. This creates inconsistent behavior—even if the admin check fails, it might incorrectly trigger the user check, or show an error message when it shouldn't.

5. Missing User Type in Session

You're only storing username in the session, so subsequent pages have no way to tell if the logged-in user is an admin or regular user. That's exactly why regular users can access admin pages—there's no account type check in those pages.

6. Insecure Password Storage

Storing plain-text passwords in your database is a critical security risk. You should always hash passwords when saving them, then verify the hash during login.

7. No exit() After Redirects

After using header("Location: ..."), you need to call exit() or die() to stop the rest of the script from running. Without this, the code might continue executing and cause unexpected session behavior.


Here's the fixed version of your code with all these issues addressed:

require('db.php');
session_start();

if (isset($_POST['username'])) {
    // Sanitize input values
    $account = mysqli_real_escape_string($con, stripslashes($_REQUEST['account']));
    $username = mysqli_real_escape_string($con, stripslashes($_REQUEST['username']));
    $password = stripslashes($_REQUEST['password']); // Don't escape password for hash verification

    // Fixed SQL query with proper condition separation
    $query = "SELECT * FROM users_detail WHERE account = '$account' AND username = '$username'";
    $result = mysqli_query($con, $query);
    
    if (mysqli_num_rows($result) === 1) {
        // Fetch the actual user record from the result
        $user = mysqli_fetch_assoc($result);
        
        // Verify password (switch to password_verify if you use password_hash for storage)
        // Important: Update your user registration code to use password_hash ASAP!
        if ($password === $user['password']) {
            // Store both username and account type in session for access control
            $_SESSION['username'] = $username;
            $_SESSION['account_type'] = $account;

            // Redirect based on account type
            if ($account === "admin") {
                header("Location: index.php");
            } else if ($account === "user") {
                header("Location: add_user.php"); // Fixed filename (spaces cause issues)
            }
            exit(); // Stop script execution after redirect
        } else {
            $error = "Username/password is incorrect.";
        }
    } else {
        $error = "Username/password is incorrect.";
    }

    // Show error message if login fails
    if (isset($error)) {
        echo "<div class='alert'> $error Click <a href='login.php'>here</a> to log-in. </div>";
    }
} else {
    // Your login form HTML goes here
?>

Critical Follow-Up Steps:

  • Password Hashing: Update your user registration code to use password_hash($password, PASSWORD_DEFAULT) when storing passwords, then replace the plain-text check with password_verify($password, $user['password']) in the login code. This is non-negotiable for security.
  • Page Access Control: Add this check at the top of admin-only pages (like index.php) to block unauthorized access:
    session_start();
    if (!isset($_SESSION['account_type']) || $_SESSION['account_type'] !== "admin") {
        header("Location: login.php");
        exit();
    }
    
    Add similar checks for user-only pages to enforce proper permissions.
  • Filename Best Practices: Avoid spaces in filenames like add user.php—use underscores (add_user.php) instead to prevent URL and server configuration issues.

内容的提问来源于stack exchange,提问作者Rchl Sy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:40:06