zach zach - 6 months ago 12
SQL Question

php login array issue

I set up an array that holds 'username' and 'password' to go through login validation functions and I keep getting the error that 'username' and 'password' is an Undefined index on line 24.

What did I do wrong? Thanks!

Here is my code:

<?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>

Answer

you never initialised $error[$fieldm].

so when you access it by $error[$fieldm] .= "...", it's the same as $error[$fieldm] = $error[$fieldm] + "..."

and before the first assignment, $error[$fieldm] does not exist.