PHP for the Web·PHP from first script to a working app

Forms and superglobals

Read GET and POST safely, validate input and escape output.

Beginner 15 min read Lesson 5 of 300 Challenge included
What you will be able to do
  • Use $_POST for form submissions and $_GET for filters.
  • Prefer filter_input for one-off validation.
  • Escape output with htmlspecialchars.
  • Show errors next to the field and keep the submitted value.

In plain English

Every value that arrives from the browser is untrusted text. Validate it, reject what you cannot accept, and escape it at the moment you print it. Never build SQL or HTML by concatenating raw input.

form.phpPHP
<?php
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$error = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$email) {
    $error = 'Enter a valid email address.';
}
?>
<form method="post">
  <label>Email <input name="email" type="email"></label>
  <button>Subscribe</button>
</form>
<?php if ($error): ?>
  <p><?= htmlspecialchars($error) ?></p>
<?php endif; ?>
Your turn

Validate a name

Medium

Accept a name from POST and print it only when it is between 2 and 60 characters after trimming.

PHP · starter
$name = trim($_POST['name'] ?? '');
Check your understanding before moving on.
Knowledge checkQuestion 1

Which superglobal contains submitted form fields sent with method="post"?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Sessions and cookies
Lesson 5 of 300 · 0% of course