PHP新手求助:登录与注册页关联异常,登录逻辑故障排查
Hey there! Let's work through your login flow issues step by step—this is super common for PHP beginners, so don't stress!
First, let's break down your two core problems:
- Wrong passwords still trigger a redirect: Your original code didn't properly check if the user's credentials matched what's in the database before sending the redirect.
- Login succeeds but stays on the login page: After adding
mysqli_num_rows, you probably have a logic gap (like missing a script termination after redirect) or an issue with how you're verifying passwords/sessions.
Let's fix this with a corrected, secure login example (and point out where you might have gone wrong):
Here's a robust version of your login code that addresses both issues:
<?php session_start(); $_SESSION['message'] = ''; // Only run logic if the form is submitted via POST if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Connect to database (fill in your full DB name where it's truncated) $mysqli = new MySQLi('127.0.0.1', 'root', '', 'your_database_name'); // Check for connection errors first if ($mysqli->connect_error) { die("Database connection failed: " . $mysqli->connect_error); } // Grab form inputs (adjust field names to match your form!) $username = trim($_POST['username']); $input_password = trim($_POST['password']); // Use prepared statements to avoid SQL injection (critical for security!) $stmt = $mysqli->prepare("SELECT id, password FROM users WHERE username = ?"); $stmt->bind_param("s", $username); $stmt->execute(); $result = $stmt->get_result(); // Check if user exists in DB if ($result->num_rows === 1) { $user = $result->fetch_assoc(); // Verify password (this assumes you used password_hash() when registering users!) if (password_verify($input_password, $user['password'])) { // Login success: Set session variables $_SESSION['user_id'] = $user['id']; $_SESSION['username'] = $username; $_SESSION['message'] = "Welcome back!"; // Redirect to your target page AND terminate the script header("Location: your_associated_page.php"); exit(); // This is easy to forget and causes the "stuck on login page" bug! } else { $_SESSION['message'] = "Incorrect password. Try again."; } } else { $_SESSION['message'] = "No account found with that username."; } // Clean up database connections $stmt->close(); $mysqli->close(); } ?> <!-- Example Login Form --> <form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <div> <label>Username:</label> <input type="text" name="username" required> </div> <div> <label>Password:</label> <input type="password" name="password" required> </div> <!-- Display status messages --> <?php if (!empty($_SESSION['message'])): ?> <p style="color: red;"><?php echo $_SESSION['message']; ?></p> <?php endif; ?> <button type="submit">Login</button> </form>
Common mistakes to check in your original code:
- Forgot to verify passwords: If you only checked if the username exists (with
mysqli_num_rows) but didn't compare the password (usingpassword_verify), wrong passwords would still pass. Also, never store plain-text passwords—usepassword_hash()when registering users. - Missing
exit()after redirect: Theheader()function sends a redirect signal, but if you don't addexit()ordie(), the rest of your script will keep running, which can override the redirect or break session setup. - SQL injection risks: If you were directly inserting user input into your SQL query (instead of prepared statements), you're opening yourself up to attacks—and possibly broken query logic.
- Session initialization issues: Make sure
session_start()is the very first line of your script (no HTML or whitespace before it), otherwise sessions won't work properly, and your target page might not recognize the logged-in user. - Reversed logic in
mysqli_num_rowscheck: If you wrote something likeif ($result->num_rows !== 1)to trigger the redirect, that would send users away even when they log in correctly.
Quick note for your registration page:
Make sure when you create user accounts, you hash the password like this:
$hashed_password = password_hash($user_password, PASSWORD_DEFAULT); // Store $hashed_password in your database's password field
Content的提问来源于stack exchange,提问作者Fragrance Resources
相关产品推荐
相关产品推荐

