PHP Form Required

PHP Form Required Fields

It is very common to have specific fields in a form that are absolutely mandatory, such as a username, email, or password. If a user tries to submit the form without filling these out, your PHP script should catch the error and warn them.


Checking if the Form was Submitted

Before we check if a field is empty, we must ensure that the form was actually submitted in the first place! We can do this by checking the $_SERVER["REQUEST_METHOD"]. If it equals "POST", it means the user clicked the submit button.

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  // The form has been submitted! Run validation checks here.
}

The empty() Function

To verify if a specific form field was left blank, we use the built-in PHP empty() function.

If a field is empty, we can store an error message in a variable to display it to the user. If it is not empty, we can pass the data through our security function from the previous chapter.

Required Fields Example

<?php
// Initialize variables to empty strings
$name = $email = "";
$nameErr = $emailErr = "";

// Simulate form submission where name is missing $_SERVER["REQUEST_METHOD"] = "POST"; $_POST["name"] = ""; $_POST["email"] = "john@example.com";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

// Check if Name is empty if (empty($_POST["name"])) { $nameErr = "Name is required!"; } else { $name = htmlspecialchars($_POST["name"]); }

// Check if Email is empty if (empty($_POST["email"])) { $emailErr = "Email is required!"; } else { $email = htmlspecialchars($_POST["email"]); }

echo "Name Error: " . $nameErr . "<br>"; echo "Validated Email: " . $email; } ?>

By maintaining variables for errors (like $nameErr), you can easily output these error messages directly next to the HTML inputs so the user knows exactly what they missed!


Exercise

?

Which PHP function is used to check if a form field was left completely blank?