PH PHP

PHP: Forms & Superglobals

What you will learn

How PHP receives form data via $_GET, $_POST, and $_SERVER, and the importance of sanitizing user input.

HTML form

<!-- form.html -->
<form method="POST" action="process.php">
    <input name="username" placeholder="Your name">
    <input type="email" name="email">
    <button type="submit">Send</button>
</form>

Processing form data

// process.php
$name = $_POST["username"];
$email = $_POST["email"];
echo "Hello, $name! Your email is $email.";

$_POST contains key-value pairs from form fields where method="POST". For GET forms, use $_GET.

Superglobals reference

Variable Contents
$_GET URL query parameters
$_POST HTTP POST body (form data)
$_SERVER Server info, headers, paths
$_SESSION Session variables (start with session_start())
$_COOKIE HTTP cookies
$_FILES Uploaded files

Sanitizing input (security!)

Never trust user input. Sanitize before outputting:

$name = htmlspecialchars($_POST["name"]);  // prevent XSS
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);

Common mistakes

  • Forgetting htmlspecialchars() — leads to cross-site scripting (XSS) vulnerabilities
  • Using $_REQUEST instead of $_GET/$_POST$_REQUEST merges both, creating ambiguity
  • Not checking if a key exists before accessing it — use isset() or the null coalescing operator ??
  • Forgetting session_start() before using $_SESSION

Quick check below!