Forms with GET and POST

View saved

Build a simple form

Save as form.html or a PHP page that emits HTML.

<form method="post" action="greet.php">
  <label>Name <input name="name"></label>
  <button type="submit">Send</button>
</form>

Read POST data

Superglobals hold request values. Check that keys exist.

<?php
$name = $_POST["name"] ?? "";
$name = trim($name);
echo "Hello, " . htmlspecialchars($name, ENT_QUOTES, "UTF-8");

GET for query strings

Links and search forms often use GET.

// /search.php?q=php
$q = $_GET["q"] ?? "";
echo htmlspecialchars($q, ENT_QUOTES, "UTF-8");

Safety basics

  • Never trust raw input
  • Escape output for HTML contexts
  • Prefer POST for actions that change data
  • Validate required fields before use

Comments

One comment per signed-in account. Comments are saved with this page’s URL.