2016-05-30 141 views
1

我設置了一個數組,其中包含'用戶名'和'密碼'以通過登錄驗證函數,並且我不斷收到第24行的'用戶名'和'密碼'是未定義索引的錯誤。php登錄陣列問題

我做錯了什麼?謝謝!

這裏是我的代碼:

<?php require_once("redirect.php"); 
require_once("proj2Functions.php"); 

$errors = []; 
$message = ""; 

if (isset($_POST["submit"])) {//1 
    $username = trim($_POST["username"]); 
    $password = trim ($_POST["password"]); 

    $fieldsRequire = array("username", "password"); 
    foreach($fieldsRequire as $field) {//2 
     $value = trim($_POST[$field]); 
     if (!has_presence($value)) {//3 
      $errors[$field] = ucfirst($field) . " can't be blank"; 
     }//3 
    }//2 
    $fieldsMax = 5; 
    foreach($fieldsRequire as $fieldm) {//4 
     $value = trim($_POST[$fieldm]); 
     if (!has_max_length($value, $fieldsMax)) {//5 
      //Line 24 
      $errors[$fieldm] .= "<br>- can't be more then {$fieldsMax}  characters."; 
     }//5 
    }//4 

    foreach($fieldsRequire as $FIELD) { 
     $value1 = trim($_POST[$FIELD]); 
     if (!specialChar($value1)) { 
      $errors[$FIELD] .= "<br>- cannot have a $ sign."; 
     } 
    } 

    if (empty($errors)) {//6 
     if ($username == "zach" && $password == "zach") {//7 
      redirect_to("Homepage2.php"); 
     } else { 
      $message = "Username/password do not match."; 
     }//8 
    }//6 
}else { 
    $username = ""; 
    $message = "Please log in."; 
} 
?> 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 

<html lang="en"> 
    <head> 
     <title>Start Collay Login(beginLogin)</title> 
    </head> 
    <body> 
     <?php echo $message; ?> 
     <?php echo formErrors($errors); ?> 
     <?php print_r($_POST); ?> 

     <form action="beginLogin.php" method="post"> 
      Username: <input type="text" name="username" value=""><br> 
      Password: <input type="text" name="password" value=""><br> 
      <input type="submit" name="submit" value="submit"> 
     </form> 
    </body> 
</html> 

回答

1

你永遠不會初始化$error[$fieldm]

,所以當你通過$error[$fieldm] .= "..."訪問,這是一樣的 $error[$fieldm] = $error[$fieldm] + "..."

和第一任務之前,$error[$fieldm]不存在。

編輯回答評論:

的清潔方法是檢查字段存在,如果沒有,用一個空字符串初始化它:

if(!isset($error[$fieldm])) { 
    $error[$fieldm] = ""; 
} 

這樣以後可以追加到它沒有檢查。

骯髒,但工作方式(不推薦)將簡單地抑制與@運營商的未定義索引錯誤,因爲在這種情況下,PHP假定一個空字符串。但是,正如我所說,不推薦。非常非常髒

+0

這很有道理。謝謝!如何將新錯誤添加到原始數組「錯誤[$ field]」? – zach