构建PHP Session平面文件认证:数组登录匹配失败求助
Hey there! Let's figure out why your CSV-generated credential array isn't working even though it looks identical to your static one. Subtle parsing quirks with CSV files are almost always the culprit here—let's break down the most likely fixes:
Hidden Whitespace in Entries
CSV files often sneak in spaces, tabs, or line breaks before/after your email/password values. Even though'user@jason.com'and'user@jason.com 'look the same, they'll fail a strict string comparison. Fix this by trimming every field as you read it:$credentials = []; if (($handle = fopen("userinfo.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $email = trim($data[0]); $password = trim($data[1]); $credentials[$email] = $password; } fclose($handle); }UTF-8 BOM or Incorrect Delimiters
If your CSV was saved with a UTF-8 BOM (byte order mark), the first email entry will have hidden characters at the start that aren't visible in your output. Additionally, some CSV files use semicolons (;) instead of commas as delimiters. To fix the BOM:$handle = fopen("userinfo.csv", "r"); // Remove UTF-8 BOM if present $bom = pack('H*','EFBBBF'); $firstLine = fgets($handle); if (strncmp($firstLine, $bom, 3) === 0) { $firstLine = substr($firstLine, 3); fseek($handle, 0); fwrite($handle, $firstLine); fseek($handle, 0); } // Now proceed with fgetcsv, adjusting delimiter if needed while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { // ... processing code ... }Case Sensitivity Mismatches
Your static array might use all lowercase emails, but your CSV could have mixed case (e.g.,User@Jason.comvsuser@jason.com). If your login logic does strict case checks, this will fail. Normalize both the stored and input values:// When reading CSV $email = strtolower(trim($data[0])); // When validating login $inputEmail = strtolower(trim($_POST['email'])); if (isset($credentials[$inputEmail]) && $credentials[$inputEmail] === trim($_POST['password'])) { // Successful login logic }Debug the Raw Array Values
Sometimes visual output is misleading. Usevar_dumpto inspect the actual length and content of each array entry, then compare to your static array:echo "CSV-generated array:\n"; foreach ($credentials as $email => $pass) { var_dump($email); var_dump($pass); } echo "\nStatic array:\n"; $staticCreds = ['user@jason.com'=>'PW123', 'user2@jason.com'=>'ABC123']; foreach ($staticCreds as $email => $pass) { var_dump($email); var_dump($pass); }Look for differences in string length or hidden characters (like
\ror\nat the end of values).
Start with trimming whitespace and debugging the raw array values—those are the quickest wins. If none of these work, share a snippet of your CSV reading code and a sample line from your CSV file, and we can dig deeper!
内容的提问来源于stack exchange,提问作者J---

