Working with Forms: GET and POST

Site Admin · 11 Sep 2026 · 8 views

Working with Forms: GET and POST

Forms are how users send data to your server. PHP exposes that data through two superglobals: $_GET and $_POST.

Building the form

<form method="post" action="subscribe.php">
  <label>Email: <input type="email" name="email" /></label>
  <button type="submit">Subscribe</button>
</form>

The submit loads subscribe.php, where the name attribute is the key your PHP reads:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  echo $_POST['email'];
}

GET vs. POST

GET sends data in the URL query string, visible in the address bar, and is best for searches and filters. POST sends data in the request body, invisible in the URL, and is right for submissions that change data.

Accessing the data

// GET /search.php?q=cat
$q = $_GET['q'] ?? '';

The null coalescing operator provides a default when the key is missing.

Always validate and sanitize

Never echo raw user input. Trim, check expected values, and escape output:

$email = trim($_POST['email'] ?? '');
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo 'Invalid email';
} else {
  echo htmlspecialchars($email, ENT_QUOTES);
}

Key Points

  • Form fields are read via $_GET or $_POST.
  • The name attribute sets the array key.
  • GET suits queries; POST suits mutations.
  • Use ?? '' to default missing keys.
  • Sanitize input and escape output at all times.
Share this post:

Comments (0)

Please login or register to comment.