PHP Tutorial · PHP for the Web · Lesson 20 of 38
PHP Superglobals
$_GET, $_POST, $_SERVER and other built-in request variables.
What are superglobals?
Superglobals are built-in arrays available everywhere, holding information about the current request:
| Variable | Contains |
|---|---|
$_GET |
query string parameters (?page=2) |
$_POST |
form fields sent with POST |
$_SERVER |
request and server info (method, path, headers) |
$_COOKIE |
cookies sent by the browser |
$_SESSION |
session data (after session_start()) |
$_FILES |
uploaded files |
Reading input safely
Never trust input. Read it with ?? for defaults, validate it, and escape it with htmlspecialchars() when printing into HTML to prevent XSS:
<?php
// Simulate a request to: /search.php?q=<script>alert(1)</script>&page=2
$_GET = ["q" => "<script>alert(1)</script>", "page" => "2"];
$q = trim($_GET["q"] ?? "");
$page = filter_var($_GET["page"] ?? 1, FILTER_VALIDATE_INT, ["options" => ["min_range" => 1]]) ?: 1;
echo "Results for: " . htmlspecialchars($q) . " (page $page)\n";
Output
Results for: <script>alert(1)</script> (page 2)
This example sets $_GET by hand so it runs here; on a real server PHP fills it from the URL search.php?q=...&page=2.
Test yourself
Which function escapes text before printing it into HTML?
strip_tags()htmlspecialchars()addslashes()escape()
Show answer
Answer: htmlspecialchars()