Skip to content
Tutorials Center
My learning

Topics

Lesson 74 of 147 ยท PHP and the Web

Handling Forms

Handle HTML forms in PHP - GET vs POST, reading fields safely, filter_var and filter_input, checkboxes and selects, sticky forms and the POST-redirect-GET pattern.

Forms are how people talk to your application: search boxes, sign-up pages, comment fields, checkout steps. The HTML side, covered in the HTML forms lesson, decides which fields exist and where they're sent. The PHP side receives the submission, makes sense of it, and decides what to show next.

Handling a form well takes more than reading $_POST['name']. You have to choose between GET and POST, cope with fields that are missing or have the wrong type, convert strings into real values, keep what the user typed when something is wrong, and make sure a reload doesn't submit an order twice. This lesson walks through each of those steps; the next one, Form Validation, goes deeper into checking values and showing error messages.

As in the Superglobals lesson, our editor has no web server, so the runnable examples simulate a submission by filling $_SERVER, $_GET and $_POST before calling the handler. The handler code is exactly what you'd deploy.

How a form reaches PHP

Here is a small form. Its action names the script that receives the data, method chooses how it's sent, and each field's name becomes an array key in PHP:

HTML
<form action="/search.php" method="get">
  <label for="q">Search</label>
  <input id="q" name="q" type="search">
  <select name="category">
    <option value="">All</option>
    <option value="books">Books</option>
    <option value="music">Music</option>
  </select>
  <button>Search</button>
</form>

Submitting "php basics" with the Books category makes the browser request /search.php?q=php+basics&category=books, and PHP fills $_GET with ['q' => 'php basics', 'category' => 'books']. With method="post", the same pairs travel in the request body and land in $_POST instead:

TEXT
POST /search.php HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 31

q=php+basics&category=books

Only fields with a name are sent. Disabled fields, unchecked checkboxes and unselected radio groups send nothing at all, so their keys are missing from the array.

GET or POST?

The choice isn't about security (both are equally visible to anyone watching an unencrypted connection, and HTTPS protects both). It's about meaning:

GET POST
Use for Reading: search, filters, pagination Changing things: sign-up, orders, comments, deletes
Data travels in The URL The request body
Bookmarkable, shareable Yes No
Safe to repeat Yes; reloading just reads again No; the browser warns before resubmitting
Size Limited by URL length (a few KB is safe) Large (limited by post_max_size, often 8 MB)
Appears in logs and history Yes No

The rule: if submitting the form changes data on the server, use POST. Search engines and browser prefetchers follow GET links freely, and you don't want a crawler to "click" a delete link.

Reading fields safely

Every field can be missing, empty, or of an unexpected type (an attacker can turn any field into an array by renaming it name[]). A robust handler reads each field once, with a default, and converts it to the type it needs. Here is a search page that handles a GET request:

PHP A GET search form with a simulated request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at what the handler does with each input: field() guarantees a trimmed string, the category is compared against a whitelist of allowed values with a strict in_array(), and the search box shows the query again (value="<?= e($query) ?>") so the user can refine it. Every printed value goes through e(), which wraps htmlspecialchars() (see PHP and HTML Templates).

Converting values with filter_var()

Form values are strings, but your code needs integers, floats, booleans and valid email addresses. The filter extension does the converting and checking in one step. filter_var($value, FILTER_VALIDATE_...) returns the converted value on success and false on failure:

Filter Accepts Returns
FILTER_VALIDATE_INT "42", " 42 ", "-7" (not "4.0" or "042") int
FILTER_VALIDATE_FLOAT "1.5", "1e3"; decimal option for "," float
FILTER_VALIDATE_BOOL "1", "true", "on", "yes" / "0", "false", "off", "no", "" bool
FILTER_VALIDATE_EMAIL "[email protected]" the string
FILTER_VALIDATE_URL "https://example.com/a?b=1" the string
FILTER_VALIDATE_IP "203.0.113.7", "::1" the string
FILTER_VALIDATE_REGEXP whatever the regexp option matches the string

Options and flags fine-tune each filter: min_range/max_range for numbers, default for a fallback, and FILTER_NULL_ON_FAILURE to tell "invalid" (null) apart from a valid false:

PHP Validating and converting with filter_var

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Read the results closely:

  • quantity became int(3): the integer filter trims surrounding whitespace.
  • price became float(12.5) because the decimal option accepted the comma.
  • gift is true because checkboxes send "on" by default.
  • newsletter is NULL: "maybe" is neither true nor false, and FILTER_NULL_ON_FAILURE reports that instead of returning a misleading false.
  • coupon is false: FILTER_REQUIRE_SCALAR rejects the array an attacker smuggled in.
  • In filter_var_array(), a field that wasn't sent comes back as NULL, while an invalid one would be false.

Avoid the old "sanitize" filters for security. FILTER_SANITIZE_STRING was deprecated in PHP 8.1 because it gave a false sense of safety, and stripping characters from input doesn't make output safe. Validate input (reject what's wrong) and escape output (with htmlspecialchars() for HTML, prepared statements for SQL). Those are two separate jobs.

filter_input() and why tests can't fake it

filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL) combines reading and filtering: it fetches the field from the original request and returns null when it's missing. It's popular in tutorials, but it has a catch: it reads the input PHP received when the request started, not the current contents of $_POST. Changing $_POST in a test or a simulation has no effect on it:

PHP filter_input ignores changes to $_GET

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

On the command line there's no request, so filter_input() returns NULL even though $_GET['page'] is set. On a real server it would work, but the same blindness makes it hard to unit-test. That's why the examples in this course (and most frameworks) read from the arrays, or from a request object, and pass the value to filter_var().

Checkboxes, radio buttons and selects

Choice fields need special care because the browser only sends the selected options, and because the value can be anything the attacker types, not just the options you listed:

  • A single checkbox is either present (usually "on", or its value) or missing. Test it with isset($_POST['agree']).
  • A checkbox group named toppings[] arrives as an array of the checked values, or not at all.
  • A radio group or select sends one value. Always check it against the allowed list.
  • A multi-select named days[] sends an array.
PHP Reading choice fields with a whitelist

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

array_intersect() keeps only submitted values that are also in the allowed list, so the invented "gold leaf" topping disappears. For the size, array_key_exists() against the SIZES map does the same job.

Sticky forms

When a submission has a problem, show the form again with the user's values still filled in. Nobody wants to retype a long form because of one typo. This is called a sticky form. Text inputs get their value attribute, textareas get their content, and choice fields get checked or selected on the options the user picked:

PHP A sticky form

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The name contains double quotes, which would break out of the value attribute without escaping. e() turns them into &quot;, so the sticky value is both correct and safe. Tiny helpers like selected() and checked() keep the template readable.

POST-redirect-GET

After a successful POST, don't render a "Thank you" page directly. If the user presses reload, the browser asks to resubmit the form and, if they agree, the order is placed twice. The fix is the POST-redirect-GET (PRG) pattern:

  1. The browser POSTs the form.
  2. The server processes it and responds with a redirect (303 See Other) to a normal page.
  3. The browser follows the redirect with a GET. Reloading now just repeats that harmless GET.

On a real server, the redirect is two lines (see HTTP Headers, Status Codes and Redirects):

PHP
<?php
// After saving the order successfully:
header('Location: /orders/1042?created=1', true, 303);
exit;   // stop here: nothing else should be sent

The simulation below models a request handler that returns a response (status, headers, body) instead of sending it, which is also how frameworks structure this:

PHP Simulating POST-redirect-GET

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The reload in step 3 shows the page again without creating a second order. The ?created=1 parameter carries the "Thanks!" message across the redirect, but notice that it also appears again on the reload, because it's part of the URL. Real applications usually store such one-time "flash messages" in the session instead, so they disappear after being shown once. When validation fails, there's no redirect: the handler re-displays the sticky form with errors and a 422 status.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A form lets users delete their account. Which method should it use?

    Requests that change data should use POST. GET requests can be repeated, prefetched, bookmarked and followed by crawlers, and their URLs end up in logs.
  2. 2. A form has <input type="checkbox" name="terms">, and the user does not tick it. What does isset($_POST['terms']) return?

    Browsers only send checked boxes. The key is missing, so isset() returns false.
  3. 3. What does filter_var('4.5', FILTER_VALIDATE_INT) return?

    The integer filter rejects anything that is not a whole number and returns false instead of rounding.
  4. 4. Why does the POST-redirect-GET pattern redirect after a successful submission?

    Without the redirect, the result page is the response to the POST, and reloading it offers to submit the same data again, for example placing an order twice.
  5. 5. In a sticky form, how should the user's previous input be put back into a text field?

    Escaping with htmlspecialchars (here through e()) and quoting the attribute keep quotes and angle brackets in the value from breaking the HTML or injecting code.

Summary

  • A field's name becomes the array key; GET forms fill $_GET from the URL, POST forms fill $_POST from the body.
  • Use GET for reading (search, filters) and POST for anything that changes data.
  • Fields can be missing (unchecked boxes, tampered requests) or arrays; read each one with a default and the expected type.
  • filter_var() validates and converts in one step (FILTER_VALIDATE_INT, FLOAT, BOOL, EMAIL, URL) and returns false on failure; FILTER_NULL_ON_FAILURE separates "invalid" from false.
  • filter_input() reads the original request, not the arrays, which makes it hard to test; read the arrays and pass values to filter_var().
  • Check choice fields against a whitelist (in_array(..., true), array_key_exists(), array_intersect()).
  • Make forms sticky by re-printing escaped values and checked/selected attributes.
  • After a successful POST, redirect (303) to a GET page so a reload can't resubmit.

Next: Form Validation