WeCodeAcademy

PHP Forms and Superglobals

On a real website, PHP receives data from forms in superglobal arrays: $_GET (data in the address) and $_POST (data in the request body). Always escape output with htmlspecialchars so users cannot inject HTML or scripts. Here we simulate a submitted form by filling $_POST ourselves.

ExamplePHP
<?php
$_POST = ["name" => "<b>Ada</b>", "age" => "36"];

$name = htmlspecialchars($_POST["name"] ?? "");
$age = (int) ($_POST["age"] ?? 0);
echo "Hello, $name. Next year you will be " . ($age + 1) . ".\n";

if (filter_var("ada@example.com", FILTER_VALIDATE_EMAIL)) {
  echo "valid email\n";
}
var_dump(filter_var("nope", FILTER_VALIDATE_EMAIL));
Output
Hello, &lt;b&gt;Ada&lt;/b&gt;. Next year you will be 37.
valid email
bool(false)

htmlspecialchars turned <b> into harmless text. Never print user input without it.

Quick check

Why use htmlspecialchars on user input before printing it?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.