PHP Form Handling

Process and validate form submissions.

✍️ 2 exercises in this lesson

A form sends data to a PHP script with method="post". The script reads it from $_POST.

Validation checklist

  • Check that required fields are not empty.
  • Validate formats with filter_var($email, FILTER_VALIDATE_EMAIL).
  • Clean input with trim().
  • Escape output with htmlspecialchars() to prevent XSS.
  • Protect forms with a CSRF token (frameworks like Laravel do this for you).

Key Takeaways: PHP Form Handling

Mastering PHP Form Handling helps you write clean and reliable PHP code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

PHP Form Handling Code Example

PHP
<?php
$errors = [];
$email = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $email = trim($_POST["email"] ?? "");
    if ($email === "") {
        $errors[] = "Email is required";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format";
    }
}
?>
<form method="post">
  <input name="email" value="<?= htmlspecialchars($email) ?>">
  <button>Subscribe</button>
</form>
<?php foreach ($errors as $error): ?>
  <p style="color:red"><?= $error ?></p>
<?php endforeach; ?>
Output
(after submitting "abc")
Invalid email format
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

PHP Form Handling Practice Exercises

Check what you learned in “PHP Form Handling”.

/ 2 solved
Fill in the blank

Escape output to prevent XSS.

echo ($name);
✓ Correct! Not quite. Try again.
Multiple choice

Which function checks that an email address is valid?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services