agyanadda@gmail.com

PHP Form Handling

PHP Forms and Web 1 min read Updated Dec 1, 2026 Topic 22 of 36

The form

<form method="post" action="">
  <input name="name">
  <button>Send</button>
</form>

The name attribute becomes the key: $_POST['name'].

GET vs POST

GET POST
data in the URL data in the request body
can be bookmarked not visible in the URL
for search and filters for login, registration, orders
limited length large data and files

Process only when submitted

if ($_SERVER['REQUEST_METHOD'] === 'POST') { ... }

Checkboxes and multiple selects

Name them with [] to get an array: name="skills[]".

Keep values after an error

value="<?= htmlspecialchars($name) ?>" so users do not retype everything.

Post/Redirect/Get

After saving, redirect with header('Location: thanks.php'); exit; so refreshing the page does not submit the form again.

Example

Example — Course enquiry form PHP
<?php
$name = '';
$skills = [];
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $course = $_POST['course'] ?? '';
    $skills = $_POST['skills'] ?? [];

    $message = 'Thank you, ' . htmlspecialchars($name) . '! You chose ' . htmlspecialchars($course)
        . ' and know: ' . htmlspecialchars(implode(', ', $skills) ?: 'nothing yet') . '.';
}
?>
<form method="post">
  <p><input name="name" placeholder="Your name" value="<?= htmlspecialchars($name) ?>"></p>
  <p>
    <select name="course">
      <option>Web Development</option>
      <option>PHP and Laravel</option>
    </select>
  </p>
  <p>
    <label><input type="checkbox" name="skills[]" value="HTML" <?= in_array('HTML', $skills) ? 'checked' : '' ?>> HTML</label>
    <label><input type="checkbox" name="skills[]" value="CSS" <?= in_array('CSS', $skills) ? 'checked' : '' ?>> CSS</label>
  </p>
  <button>Send enquiry</button>
</form>
<p><?= $message ?></p>

After submitting, the page shows: Thank you, Asha! You chose PHP and Laravel and know: HTML, CSS. The name and checkboxes keep their values.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which method should a login form use?

Exercise 2 True / False

A checkbox group named skills[] arrives in PHP as an array.

Exercise 3 Fill in the Blank

The HTML ___ attribute of an input becomes its key in $_POST.

Frequently Asked Questions

header() must run before any output (even a space or HTML). Do your processing at the top of the file before printing anything.