PHP Form Handling

PHP form handling is the process of receiving the data a visitor submits through an HTML form and turning it into something your script can safely use.

The two halves of a form

Every PHP form involves two cooperating pieces: the HTML form that the visitor fills in, and the PHP code that runs when the form is submitted. The form's method attribute decides whether the data arrives in $_GET or $_POST, and its action attribute names the script that will process it. A common and convenient pattern is to point the action back at the same page, so one file both displays the form and handles its submission.

When the visitor presses submit, the browser sends a new request. Your PHP code checks whether that request carried form data, reads the fields it needs, and responds accordingly. Detecting the request method is the usual way to tell a fresh page load apart from a submission.

A self-processing form

<?php
$greeting = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    if ($name !== '') {
        $greeting = "Hello, " . htmlspecialchars($name) . "!";
    }
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
  <input type="text" name="name">
  <button type="submit">Greet me</button>
</form>
<p><?php echo $greeting; ?></p>
Note: Everything a visitor submits is untrusted input. Before you display it, store it, or query with it, you must sanitise and validate it. Echoing raw form data straight back into the page allows cross-site scripting; feeding it into SQL without prepared statements allows injection. Treat htmlspecialchars on output and prepared statements for the database as non-negotiable habits.

Choosing GET or POST

The right method depends on what the form does. If the submission only reads or searches, GET keeps the result shareable through its URL. If it changes something on the server or carries sensitive fields, POST keeps the data out of the URL and out of browser history.

SituationRecommended method
Search box or filterGET
Login or registrationPOST
Adding or editing a recordPOST
Pagination linkGET
Deleting somethingPOST

Reading fields defensively

A field that the visitor left blank, or that never existed, will be missing from the superglobal. Reading a missing key directly raises a warning, so use the null coalescing operator to supply a default, and trim surrounding whitespace so a field of only spaces counts as empty.

A small reusable helper

<?php
function field(string $key): string {
    // Read a POST field, defaulting to an empty string, and trim it.
    return trim($_POST[$key] ?? '');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email   = field('email');
    $subject = field('subject');
    echo "Email: "   . htmlspecialchars($email)   . "<br>";
    echo "Subject: " . htmlspecialchars($subject);
}
?>

A typical handling flow

  • Detect whether the request is a submission by checking the request method
  • Read each expected field with a safe default
  • Sanitise and validate every value against the rules you expect
  • If anything is wrong, redisplay the form with helpful error messages
  • If everything is valid, perform the action and confirm the result
Note: After a successful POST that changes data, redirect the browser to a fresh page instead of rendering directly. This Post/Redirect/Get pattern stops a page reload from resubmitting the form.

Exercise: PHP Form Handling

Why pass submitted form data through htmlspecialchars() before displaying it?