PHP ยท Chapter 25 of 44

PHP Form Validation

Form validation ensures that data submitted by users meets certain requirements before your application processes it, such as checking that required fields are filled in and emails are properly formatted.

Validation should always happen on the server side (in PHP) even if you also validate on the client side with JavaScript, because client-side checks can be bypassed by disabling JavaScript or sending requests directly.

Syntax
if (empty($_POST["name"])) { }
filter_var($email, FILTER_VALIDATE_EMAIL);

Checking required fields

empty() checks whether a variable is empty or unset, which is useful for verifying that required form fields were actually filled in.

Validating formats

filter_var() with filters like FILTER_VALIDATE_EMAIL checks that a value matches an expected format, such as a valid email address.

Example 1 (php)
<?php
  $name = "";
  if (empty($name)) {
    echo "Name is required";
  }
?>
Output
Name is required

empty() detects that $name is an empty string and triggers the error message.

Example 2 (php)
<?php
  $email = "test@example.com";
  if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email";
  } else {
    echo "Invalid email";
  }
?>
Output
Valid email

filter_var() with FILTER_VALIDATE_EMAIL confirms the string is a properly formatted email address.

Key points

  • Server-side validation is essential and cannot be skipped even with client-side checks.
  • empty() checks for missing or blank required fields.
  • filter_var() validates formats like email addresses and URLs.
  • Always show clear error messages when validation fails.
๐Ÿ’ก Note: Never trust data from $_GET or $_POST until it has been validated and sanitized on the server.

๐Ÿ“ Quick Quiz

1. Why is server-side validation still needed even with JavaScript validation?

2. Which function checks if a variable is empty?

3. Which filter validates an email address format?