PHP forms: GET, POST and safe output

Beginner  Nov 20, 2026

How data travels from a form to PHP, which method to use, and how to print it back without opening a security hole.

PHP forms: GET, POST and safe output
The steps of this tutorial at a glance.
The steps of this tutorial at a glance.

GET and POST

  • GET puts the data in the address (search.php?q=php). Use it for searching and filtering, because the page can be bookmarked and shared.
  • POST sends the data in the request body. Use it for anything that changes something (login, saving, deleting) or is private.
GET and POST
GET and POST

A simple form

<form method="post" action="hello.php">
  <label for="name">Your name</label>
  <input id="name" name="name" required maxlength="80">
  <button>Send</button>
</form>
How the code in this section fits into the page.
How the code in this section fits into the page.

Reading it in PHP

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim((string)($_POST['name'] ?? ''));

    if ($name === '') {
        $error = 'Please type your name.';
    } else {
        echo 'Hello, ' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
    }
}

Three habits are worth building from day one:

1. Use ?? so a missing field does not cause a warning.
2. Trim and check every value on the server. Browser checks such as required can be bypassed.
3. Escape when printing with htmlspecialchars(). If a visitor types <script>, it is shown as text instead of running (this stops XSS).

How the code in this section fits into the page.
How the code in this section fits into the page.

Do not do this

echo $_GET['q'];                       // prints raw input: unsafe
$sql = "SELECT * FROM t WHERE a='$x'"; // builds SQL from input: unsafe

For databases, use prepared statements (see the tutorial on prepared statements).

After a POST, redirect

If the page just saved something, redirect to another page so a browser refresh does not send the form twice:

header('Location: thanks.php', true, 303);
exit;

More tutorials