Thuta Learning
IntermediateProgrammingbeginner

Handling Forms

Relax. We'll talk through this in plain words — no textbook voice.

Form handling is everyday work for PHP web apps. Contact forms, login forms, order forms, feedback forms — they all need the server to receive and process user input. Whenever you handle form data, keep validation, sanitization, error messages, and success messages properly organized.

php
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
  <label>Name:</label>
  <input type="text" name="fname">
  <button type="submit">Send</button>
</form>

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

  if ($name === "") {
    echo "Name is required.";
  } else {
    echo "Hello, " . htmlspecialchars($name);
  }
}
?>
You should see
Fill in Name and click Send to see Hello, [Name]. Leave it blank and you'll see Name is required.

Easy traps

  • Accessing $_POST['fname'] directly when the field doesn't exist can trigger an undefined array key warning. Use ?? instead.
Handling Forms | Thuta Learning