You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

PHP登录系统错误提示异常问题求助

Fixing Your Login System's Persistent Error Message & Session Issues

Hey there! Let's walk through the problems in your code and get your login system working as intended.

Key Issues Identified

  1. Persistent Error Message
    Right now, your error text "Username or password are wrong" shows up every time the user isn't logged in—even before they've tried submitting the login form. That's because it’s directly hardcoded in the else block that renders the login form. We only want this message to appear after the user submits an invalid login attempt.

  2. Missing session_start()
    You mentioned you didn’t call session_start() at the top of your PHP file. This is non-negotiable: without it, PHP can’t manage the $_SESSION superglobal, so your login state won’t persist between page loads (even if the rest of your logic works correctly).

Revised Code with Fixes

// Add this at the VERY TOP of your PHP file, before any HTML/output!
session_start();

class login {
    public function __construct($db){
        $this->db = $db;
    }
    public function show($conn) {
        $form = "";
        $loginError = ""; // Variable to hold error message only when needed

        // Handle logout
        if (isset($_POST['logout'])) {
            $_SESSION = array();
            session_destroy(); // Fully clear the session instead of just emptying it
            // header('Location:http://localhost:8080/php/OOP/OOP-3/index.php?controller=content&action=getContent');
        }

        // Handle login submission
        if (isset($_POST['login']) && isset($_POST['username']) && isset($_POST['password'])){
            $user = $_POST['username'];
            $pass = $_POST['password'];
            
            // Optimization: Query directly for matching user instead of fetching all users
            // This is more efficient and reduces unnecessary data handling
            $sql = $this->db->select2assoc("SELECT * FROM users WHERE username = ? AND password = ?", [$user, $pass]);
            
            if (!empty($sql)) {
                // Login successful
                $_SESSION['login'] = true;
                $_SESSION['username'] = $sql[0]['username'];
            } else {
                // Login failed: Set error message
                $loginError = '<p style="color: red;">Username or password are wrong</p>';
            }
        }

        // Build authenticated user interface
        if (isset($_SESSION['login']) && $_SESSION['login'] == true && isset($_SESSION['username'])) {
            $form .= '<form action="#" method="post"><br>';
            $form .= '<input type="submit" name="logout" value="logout">';
            $form .= '</form>';
            $form .= '<p>You are logged in as '.$_SESSION['username'].'</p>';
        } else {
            // Build login form + error message (only if login failed)
            $form .= '<form action="#" method="post">';
            $form .= 'username <input type="text" name="username" size="17"><br>';
            $form .= 'password <input type="password" name="password" size="17"><br>';
            $form .= '<input type="submit" name="login" value="login">';
            $form .= '</form>';
            $form .= $loginError; // Add error message only when it's set
        }

        return $form;
    }
}

What Changed?

  • Added session_start() at the top to enable PHP session management.
  • Created a $loginError variable that only gets populated when a login attempt fails, so the message doesn’t show unnecessarily.
  • Moved the error message output to use this variable, ensuring it only appears after a failed submission.
  • Optimized the database query to directly fetch matching users (instead of looping through all user records), which is more efficient.
  • Added session_destroy() to the logout logic to fully clear the user’s session.

Quick Security Notes

  • Password Storage: Storing plain-text passwords in your database is a major security risk. Use password_hash() when creating user accounts and password_verify() to check login credentials.
  • SQL Injection: Ensure your select2assoc method supports prepared statements (the revised query uses parameterized placeholders ? to avoid injection risks).

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

火山引擎 最新活动