PHP Session无法正常工作返回Null,跨页获取ID始终为Null问题排查
Hey there, let's dig into why your PHP session is returning null when trying to fetch the user ID on another page—your login code has a couple of clear issues, plus some extra best practices we should cover.
Key Problems in Your Current Login Code
Let's break down the immediate culprits first:
session_start()is commented outYour code has
// session_start();which means PHP never initializes the session. Sessions requiresession_start()to be called before any output on every page that uses session data—including your login page and the page where you're trying to access$_SESSION['userid']. Without this,$_SESSIONvariables won't persist across page loads, leading to null values.Incorrect access to
$userSet
ThefetchAll()method returns an array of user rows (even if only one user matches your query). Right now you're trying to access$userSet['userid'](based on your truncated code), but you need to target the first element of the result array first—like$userSet[0]['userid'](adjust the column name to match your actual database schema).
Step-by-Step Corrected Code
Here's the fixed version of your login method, with added security and best practices:
public function login($email, $password) { $db = new database(); // Critical: Initialize the session before using $_SESSION session_start(); // Important: Use prepared statements to block SQL injection (never directly insert user input into queries!) $q = "select * from user where email=? AND password=?"; // Assuming your pQuery method supports prepared statements (adjust syntax if your DB class works differently) $db->pQuery($q, [$email, $password]); $userSet = $db->fetchAll(); if (!empty($userSet)) { $_SESSION["username"] = $email; // Access the first matching user's ID from the result set $_SESSION["userid"] = $userSet[0]['userid']; // Replace 'userid' with your actual database column name // Optional: Redirect to a protected page after successful login (prevents resubmitting the form on refresh) header("Location: dashboard.php"); exit(); } else { // Handle invalid login attempt echo "Invalid email or password"; } }
Additional Checks for Session Persistence
- Call
session_start()on every page using sessions: The page where you're trying to retrieve$_SESSION['userid']must also start withsession_start();(before any HTML, whitespace, or echo statements—output before this breaks session initialization). - Avoid plain-text passwords: Storing raw passwords in your database is a massive security risk. Use
password_hash()when creating user accounts andpassword_verify()to check login credentials instead of comparing plain strings. - Verify session cookie settings: Check your PHP configuration (via
phpinfo()) to ensuresession.cookie_enabledis set toOn—disabled cookies will break session persistence.
内容的提问来源于stack exchange,提问作者Mohammad Hani Hassoun

