All posts
PHPOctober 6, 20268 min read

PHP Form Validation for Beginners: Simple Step-by-Step

Learn PHP form validation for beginners: check empty fields, validate emails and show clear errors with simple, copy-paste code and line-by-line explanations.

F
Fepiq Team
Fepiq

PHP form validation for beginners means checking what a visitor typed into a form before you use it. In plain words: you make sure the name is not empty, the email looks like an email, and the age is a real number. If something is wrong, you show a friendly message instead of saving bad data.

This guide assumes you know nothing about validation. We build one small form step by step. Every term is explained the first time it appears, and every code block is followed by a line-by-line explanation.

What is form validation and why do you need it?

A form lets visitors send information to your website. Validation is the step where your PHP code checks that information. Visitors make typing mistakes. Some visitors also send bad data on purpose. You should never trust what comes from a form.

  • Empty fields: the visitor skipped a required box.
  • Wrong format: an email like "hello" with no @ sign.
  • Wrong type: letters typed where a number is expected.
  • Unsafe text: HTML or script tags that could break your page.

There are two kinds of work here. Validation checks that data is correct. Sanitizing cleans the data, for example by removing extra spaces or dangerous characters. Good forms do both.

Step 1: Build a simple HTML form

We start with a form that asks for a name and an email. The form sends its data to the same page using the POST method. If you are not sure what POST means, read our guide on PHP form handling first (link below).

php
<form method="post" action="">
  <label>Name: <input type="text" name="name"></label>
  <label>Email: <input type="text" name="email"></label>
  <button type="submit">Send</button>
</form>

Line 1 opens the form. method="post" hides the data from the web address, and action="" sends it back to the same page. Lines 2 and 3 are input boxes. The name attribute is important, because PHP uses it to find the value. Line 4 is the submit button.

New to forms? Read our PHP form handling guide first, then come back here.

Read: PHP form handling (GET vs POST)

Step 2: Check that the form was submitted

When someone first opens the page, the form is empty. We only want to validate after they press the button. PHP stores request details in a built-in array called $_SERVER. One of its values tells us the request method.

php
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    echo "The form was submitted.";
}

Line 1 starts PHP. Line 2 asks: was this page requested with POST? The triple equals sign checks for an exact match. If yes, the code inside the braces runs. On a normal page visit the method is GET, so nothing happens.

Step 3: Read the values safely

PHP puts submitted values in another built-in array called $_POST. You read a value with its input name. A field may be missing, so we use the null coalescing operator (??). It gives a default value when the key does not exist, which avoids errors.

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

$_POST["name"] gets the typed name. ?? "" means: if it is missing, use an empty string. trim() removes spaces at the start and end, so a name made of only spaces counts as empty.

Step 4: Validate each field

Now we check the values. We collect problems in an array called $errors. If the array is empty at the end, the form is valid.

php
$errors = [];

if ($name === "") {
    $errors["name"] = "Please enter your name.";
} elseif (strlen($name) > 50) {
    $errors["name"] = "Name must be 50 characters or fewer.";
}

if ($email === "") {
    $errors["email"] = "Please enter your email.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors["email"] = "That email address does not look right.";
}

Line 1 creates an empty list of errors. The name check says: if it is empty, add a message; else if it is longer than 50 characters, add a different message. strlen() counts characters. For the email, filter_var() with FILTER_VALIDATE_EMAIL is PHP's built-in email checker. The ! means "not", so the error is added when the email is not valid.

Useful built-in validation tools

ToolWhat it doesExample
trim()Removes spaces at both endstrim(" Ann ")
strlen()Counts charactersstrlen("Ann") gives 3
filter_var() with FILTER_VALIDATE_EMAILChecks email formatfilter_var($email, FILTER_VALIDATE_EMAIL)
filter_var() with FILTER_VALIDATE_INTChecks for a whole numberfilter_var($age, FILTER_VALIDATE_INT)
htmlspecialchars()Makes text safe to show on a pagehtmlspecialchars($name)

Step 5: Show errors and keep what the user typed

If there are errors, show them. Nobody likes retyping everything, so we also put the typed values back in the boxes. Because we print user text into HTML, we wrap it in htmlspecialchars(). This turns characters like < and > into harmless text and helps prevent a problem called cross-site scripting (XSS).

php
<form method="post" action="">
  <label>Name:
    <input type="text" name="name"
           value="<?= htmlspecialchars($name ?? "") ?>">
  </label>
  <span><?= $errors["name"] ?? "" ?></span>

  <label>Email:
    <input type="text" name="email"
           value="<?= htmlspecialchars($email ?? "") ?>">
  </label>
  <span><?= $errors["email"] ?? "" ?></span>

  <button type="submit">Send</button>
</form>

<?= ... ?> is a short way to print a PHP value inside HTML. The value attribute refills the box with what the visitor typed, made safe by htmlspecialchars(). The span after each box prints that field's error message, or nothing if there is none.

Step 6: Do the real work only when there are no errors

php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // ... read and validate as shown above ...

    if (empty($errors)) {
        echo "Thanks, " . htmlspecialchars($name) . "!";
        // Safe to save to a database or send an email here
    }
}

empty($errors) is true when the list has no problems. Only then do we thank the user and continue. This is where you would save the data. If you save to a database, always use prepared statements; see our guide on inserting form data into a database.

Ready to save validated data? Learn how to insert form data into a database with PHP.

Read: Insert form data with PHP

Common beginner mistakes

  • Relying only on HTML attributes like required. Visitors can bypass them, so always validate in PHP too.
  • Forgetting trim(), which lets a name of only spaces pass.
  • Printing user input without htmlspecialchars().
  • Reading $_POST["name"] without ?? and getting an undefined key warning.
  • Showing one vague message like "Invalid form" instead of a clear message per field.

Frequently asked questions

What is form validation in PHP?+

Form validation is checking the data a visitor sent through a form before you use it. You test that required fields are filled, that formats such as email are correct, and that lengths are reasonable. Invalid data gets an error message instead of being saved.

How do I validate an email in PHP?+

Use filter_var($email, FILTER_VALIDATE_EMAIL). It returns the email if the format is valid and false if not. It only checks the format, not whether the mailbox really exists.

What is the difference between validation and sanitization?+

Validation checks whether data is acceptable and rejects it if not. Sanitization changes data to make it safe or clean, such as trimming spaces or escaping HTML. Most forms need both.

Is the HTML required attribute enough?+

No. The required attribute is only a convenience in the browser, and anyone can remove or skip it. You must always validate again on the server in PHP.

What does htmlspecialchars() do?+

It converts special characters like < and > into safe HTML codes. That way, text typed by a visitor is shown as text and not run as code in the browser. Use it whenever you print user input on a page.

Want help building safe, professional forms for your website? Talk to the Fepiq team.

Contact Fepiq

Get new posts in your inbox

Occasional, no-fluff notes on shipping modern software — startups, automation, Laravel, Shopify and more. No spam, unsubscribe anytime.

Keep reading

Related posts

All posts

Let's build something

Ready to ship your next product with Fepiq?

Book a free discovery call. We'll listen, ask sharp questions, and send you a proposal within 3 business days.