Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🔴 Advanced  ·  Lesson 27

PHP Form Validation (Full Code)

In this lesson: Validate PHP forms server-side — required fields, email, numbers, sanitize and show errors — full working code.

Why validate input

Any data that comes from a user's form cannot be trusted — it might be empty, wrong, or even harmful. Validation checks that the input is correct, and sanitization cleans it so it is safe to use and display. Doing both protects your data and your website.

⚠️ Golden rule: never trust user input. Always validate on the server in PHP, even if the browser also checks.

Trim and sanitize

First clean the raw input — remove stray spaces and make it safe to display.

<?php
  $name = trim($_POST["name"] ?? "");
  $name = htmlspecialchars($name);
  echo $name;
?>

trim removes accidental spaces. htmlspecialchars turns characters like < into safe text, which stops users injecting HTML or scripts (an XSS attack).

Checking required fields

Make sure important fields are not empty, and collect any errors.

<?php
  $errors = [];
  $name = trim($_POST["name"] ?? "");
  if ($name === "") {
      $errors[] = "Name is required";
  }
  if (empty($errors)) {
      echo "Form OK";
  } else {
      echo $errors[0];
  }
?>
Name is required

Collecting errors in an array lets you check every field and show all problems together, instead of stopping at the first one.

Validating an email

Do not write your own email check — use PHP's built-in filter.

<?php
  $email = "aman@site.com";
  if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
      echo "Valid email";
  } else {
      echo "Invalid email";
  }
?>
Valid email

filter_var with FILTER_VALIDATE_EMAIL is reliable and handles the tricky rules of real email addresses for you.

A full example

<?php
  $errors = [];
  $name  = trim($_POST["name"]  ?? "");
  $email = trim($_POST["email"] ?? "");

  if ($name === "")  $errors[] = "Name required";
  if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Valid email required";

  if (empty($errors)) {
      $name = htmlspecialchars($name);
      echo "Welcome, $name";
  } else {
      foreach ($errors as $e) echo $e . "<br>";
  }
?>

This pattern — trim, validate, collect errors, then act — is the standard, safe way to handle any PHP form.

Common mistakes

  • Trusting browser validation only. It can be bypassed; always re-check in PHP.
  • Not using htmlspecialchars when displaying input. This opens the door to XSS.
  • Forgetting to trim. Hidden spaces cause failed checks and duplicate records.
  • Writing your own email regex. Use filter_var instead — it is correct and simple.

Summary

  • Never trust user input — validate and sanitize on the server.
  • trim cleans spaces; htmlspecialchars makes input safe to display.
  • Check required fields and collect errors in an array.
  • Validate email with filter_var($e, FILTER_VALIDATE_EMAIL).
  • Always re-validate in PHP even if the browser checks too.

Next, protect pages further with XSS prevention, or store submitted data using sessions and cookies.

Frequently Asked Questions

What is the difference between validation and sanitization?
Validation checks whether the input is correct (is it a real email? is the field filled?). Sanitization cleans the input to make it safe (removing dangerous characters). You usually sanitize first, then validate.
How do I check a valid email in PHP?
Use filter_var($email, FILTER_VALIDATE_EMAIL). It returns the email if it is valid, or false if not. This is far more reliable than writing your own check.
Why must I use htmlspecialchars when showing user input?
htmlspecialchars() turns characters like < and > into safe text so a user cannot inject HTML or scripts into your page. It is a key defence against XSS attacks.
Why trim form input?
Users often add accidental spaces. trim() removes leading and trailing spaces so " aman@site.com " is stored correctly and comparisons work as expected.
Should I rely only on browser (HTML) validation?
No. Browser validation can be bypassed. Always validate again on the server in PHP, because that is the only check an attacker cannot skip.
← Back to PHP Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicArray Functions Your progress: 27 / 50 (54%) · Lesson 28 / 50 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free