Working with Superglobals and Forms
PHP gives you built-in “superglobal” arrays for reading request data — this is how a script finds out what a visitor submitted through a form, or what parameters were included in the URL.
<form method="post" action="submit.php">n <input type="text" name="username">n <button type="submit">Send</button>n</form>
// inside submit.phpn$username = $_POST["username"] ?? "";necho "Welcome, " . htmlspecialchars($username);
Always sanitize and escape
htmlspecialchars() converts special characters like < and > into their safe HTML-entity equivalents, so submitted text can never be rendered as actual HTML or executable script. Skipping this step is precisely how sites become vulnerable to cross-site scripting (XSS) attacks — an attacker could submit a form field containing a <script> tag that, unescaped, would run in every visitor’s browser who later views that data. Never trust $_POST, $_GET, or $_COOKIE data directly, in any PHP application.
Other common superglobals
$_GET— data from the URL query string, like?id=42$_POST— data submitted through an HTML form using the POST method$_SESSION— data that persists across multiple requests for one visitor, commonly used for login state$_SERVER— details about the request and the server itself, like the requested URL or the visitor’s IP address$_COOKIE— small pieces of data stored in the visitor’s browser and sent back on every request
Validating input, not just escaping it
$age = $_POST["age"] ?? "";nif (!is_numeric($age) || $age < 0) {n echo "Please enter a valid age.";n} else {n $age = (int) $age;n // safe to use $age nown}
Escaping protects against malicious HTML/script content; validation checks that the data is actually the shape you expect in the first place (a real number, a valid email format, and so on). A production application needs both — one alone is not enough.