PHP登录系统错误提示异常问题求助
Hey there! Let's walk through the problems in your code and get your login system working as intended.
Key Issues Identified
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 theelseblock that renders the login form. We only want this message to appear after the user submits an invalid login attempt.Missing
session_start()
You mentioned you didn’t callsession_start()at the top of your PHP file. This is non-negotiable: without it, PHP can’t manage the$_SESSIONsuperglobal, 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
$loginErrorvariable 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 andpassword_verify()to check login credentials. - SQL Injection: Ensure your
select2assocmethod supports prepared statements (the revised query uses parameterized placeholders?to avoid injection risks).
内容的提问来源于stack exchange,提问作者JvdLelie




