I am currently learning to validate forms in PHP and parts of my code aren't producing the desired output. I'd want the code to print out Username cant be blank
when the user submits the form without a username and Password cant be blank
when the password field is left blank while submitting. i have marked out, with the help of comments, the lines of code that were meant to achieve this goal (refer: //DOESNT WORK
). Currently, the code is successfully able to display to the user Username/Password dont match
. I am running the php scripts on XAMPP. My code:
form_with_validation.php
<?php
require_once("included_functions.php");
require_once("validation_functions.php");
$errors = array();
$message = "";
if(isset($_POST['submit']))
{ //form was submitted
$username = trim($_POST["username"]);
$password = trim($_POST["password"]);
//Validations
$fields_required = array("username", "password");
foreach($fields_required as $field) //DOESNT WORK
{
$value = trim($_POST[$field]);
if(!has_presence($value))
{
$errors[$field] = ucfirst($field) . " cant be blank.";
}
}
if(empty($errors))
{
//try to login
if($username == "mickey" && $password == "password")
{ //successful login
redirect_to("basic.html");
}
else
{
$message = "Username/Password dont match.";
}
}
}
else {
$username = "";
$message = "Please Log in.";
}
?>
<html lang = "en">
<head>
<title>Form</title>
</head>
<body>
<?php echo $message; ?> <br>
<?php echo form_errors($errors);?>
<form action="form_with_validation.php" method = "post">
Username: <input type="text" name="username" value="<?php echo htmlspecialchars($username)?>" /><br>
Password: <input type="password" name="password" value=""/><br>
<br>
<input type="submit" name= "submit" value="Submit" />
</form>
</body>
validation_functions.php
<?php
//presence
function has_presence($value)
{
return isset($value) || $value !== "";
}
//string length
//max length
function has_max_length($value, $max)
{
return strlen($value) <= $max;
}
//inclusion in a set
function has_inclusion_in($value, $set)
{
return in_array($value, $set);
}
function form_errors($errors=array())
{
$output = "";
if(!empty($errors))
{
$output .= "<div class=\"error\">";
$output .= "Please fix the following errors:"; //NOT WORKING
$output .= "<ul>";
foreach($errors as $key => $error)
{
$output .= "<li>{$error}<li>";
}
$output = "</ul>";
$output .= "</div>";
}
return $output;
}
?>
included_functions.php
{
return "Hello {$name}!";
}
function redirect_to($new_location)
{
header("Location: " . $new_location);
exit;
}
?>