<?php
// Define variables and set empty values
$name = $email = "";
$nameErr = $emailErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Check if Name is empty
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
// Check if Email is empty
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
}
// Function to sanitize input
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Required Field Validation</title>
</head>
<body>
<h2>PHP Required Field Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Name: <input type="text" name="name" value="<?php echo $name; ?>">
<span style="color: red;">* <?php echo $nameErr; ?></span><br><br>
Email: <input type="text" name="email" value="<?php echo $email; ?>">
<span style="color: red;">* <?php echo $emailErr; ?></span><br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
// Display success message if no errors
if ($_SERVER["REQUEST_METHOD"] == "POST" && $nameErr == "" && $emailErr == "") {
echo "<h3>Form Submitted Successfully</h3>";
echo "Name: " . $name . "<br>";
echo "Email: " . $email . "<br>";
}
?>
</body>
</html>