Explain it simply
Explain it simply
Superglobals are built-in variables that PHP creates for you. Each time a browser sends a request, PHP puts the URL's query string into $_GET, form data into $_POST, cookies into $_COOKIE, and facts about the server and the request into $_SERVER, and only then starts running your script. You never have to ask for them.
"Super" means you can read them from anywhere, even inside a function, without the global keyword. It also pays to remember that the values inside them are chosen by the visitor (or an attacker), so they count as untrusted input. This lesson covers what exists, why they are empty on the command line, and how to read them safely.
Problem → Why → Solution
The problem: empty on the command line, untrustworthy on the web
When you first try superglobals, you meet one of two surprises. The first is running php script.php in a terminal and reading $_SERVER["REQUEST_METHOD"], which prints Warning: Undefined array key "REQUEST_METHOD". The CLI has no web request, so $_GET, $_POST and $_COOKIE are empty arrays and $_SERVER lacks the web-related keys. Reading $_SESSION before session_start() has run gives Warning: Undefined global variable $_SESSION.
The second surprise happens on the web, when you trust the values automatically. Putting $_GET["id"] straight into SQL, using $_SERVER["HTTP_HOST"] to build links, or opening an admin path because $_COOKIE["isAdmin"] says so all rest on values an attacker can choose.
<?php
// 1. In the CLI there is no request: this prints a warning
echo "Method: " . $_SERVER["REQUEST_METHOD"] . "\n";
// 2. On the web, each of these values is chosen by the visitor
$id = $_GET["id"]; // could be "5 OR 1=1" or an array
$link = "https://" . $_SERVER["HTTP_HOST"] . "/reset"; // Host header is client-supplied
if ($_COOKIE["isAdmin"] === "1") { // cookies can be edited in the browser
echo "Welcome, admin";
}Why does this happen?
PHP does not write the request itself; it only fills these arrays with data received from the web server (or PHP-FPM). On the command line there is no such request, hence the emptiness. On the web every value is text sent by someone else, so its shape, length and type must all be checked rather than trusted. The cure is to read values with defaults, validate the selected fields, and pass the clean values into functions.
Core concept: arrays PHP fills from the request
Superglobals are ordinary arrays that PHP fills before a request reaches your script. The main ones are $_GET (the URL query string), $_POST (the form body), $_COOKIE (the Cookie header), $_FILES (uploaded files), $_SERVER (server, PHP and request-header facts), $_SESSION (server-side storage, available after session_start()), $_REQUEST (a merge of some sources, best avoided) and $GLOBALS (every global variable). Because they are plain arrays you can assign to them, which is exactly how we simulate a request in the CLI.
| Superglobal | Filled from | Who controls it |
|---|---|---|
| $_GET | the URL's query string | the visitor |
| $_POST | the form body (urlencoded or multipart) | the visitor |
| $_COOKIE | the Cookie header | the visitor (editable in the browser) |
| $_SERVER | web server + PHP + HTTP_* headers | mixed: HTTP_* keys come from the visitor |
| $_SESSION | server-side storage | your code (the session ID travels in a cookie) |
Under a web server (Apache with PHP-FPM, nginx with PHP-FPM and so on) PHP parses the request and fills these arrays. In the CLI there is no request, so $_GET, $_POST and $_COOKIE are empty, and $_SERVER holds command-line entries such as argv and argc but no REQUEST_METHOD. That is why the samples in this course assign $_GET or $_SERVER at the top of the script to imitate a request.
The key rule: the names in $_GET, $_POST, $_COOKIE and $_FILES, and every $_SERVER key that starts with HTTP_, are chosen by whoever sent the request, including an attacker using curl. The values are also only ever strings or arrays: ?tag[]=a produces an array, so trim($_GET["tag"]) can throw a TypeError, and nothing arrives as an int. The best practice is to read raw superglobals in one place at the edge of the program, clean the selected fields with trim, type checks and filter_var, and pass them into functions as parameters. Then those functions can be tested with plain arrays and no web server.
- Browser sends the request
- PHP fills $_GET, $_SERVER and co.
- At the edge, pick fields and check
- Pass clean values as parameters
In the CLI you perform the first two steps yourself: assign the arrays to imitate a request.
General pattern
$value = $_GET["key"] ?? "default"; // read with a fallback
$method = $_SERVER["REQUEST_METHOD"] ?? "GET";
// web: filled by PHP. CLI: assign it yourself.
$_GET = ["key" => "value"];
parse_str($queryString, $_GET); // build $_GET from a query string
function handle(array $get, array $server): string
{
// work with parameters, not with raw superglobals
}?? gives a default without a warning when the key is missing. parse_str() turns a query string into an array the way PHP itself does, so shapes like ?tag[]=a can be simulated faithfully. A function such as handle(array $get, ...) reads only its array parameters, which makes it easy to test.
Example: simulating a GET request in the CLI
This script first shows that the superglobals are empty in the CLI. It then fills $_SERVER and $_GET by hand, the way a web server would for GET /shop.php?category=books&page=2. describeRequest() reads those values without the global keyword. Under a real web server you would simply delete the assignment part.
<?php
// The CLI has no web request, so the request superglobals start out empty.
echo "SAPI: ", PHP_SAPI, "\n";
echo "GET parameters: ", count($_GET), "\n";
echo "Has REQUEST_METHOD: ", isset($_SERVER["REQUEST_METHOD"]) ? "yes" : "no", "\n";
// Imitate what a web server would fill in for: GET /shop.php?category=books&page=2
$_SERVER["REQUEST_METHOD"] = "GET";
$_SERVER["REQUEST_URI"] = "/shop.php?category=books&page=2";
parse_str(parse_url($_SERVER["REQUEST_URI"], PHP_URL_QUERY) ?? "", $_GET);
function describeRequest(): string
{
// superglobals are visible inside functions: no global keyword needed
$method = $_SERVER["REQUEST_METHOD"] ?? "UNKNOWN";
$category = $_GET["category"] ?? "all";
$page = (int) ($_GET["page"] ?? 1);
return "$method category=$category page=$page";
}
echo describeRequest(), "\n";Code breakdown
- Empty in the CLI
echo "GET parameters: ", count($_GET), "\n";With no request in the CLI, $_GET is an empty array and its count is 0. PHP_SAPI reporting cli confirms that this is not a web run.
- Simulate the method
$_SERVER["REQUEST_METHOD"] = "GET";$_SERVER is assigned like any array. Under a web server PHP would fill this key in for you.
- Build $_GET from the URL
parse_str(parse_url($_SERVER["REQUEST_URI"], PHP_URL_QUERY) ?? "", $_GET);parse_url() extracts the query string from the URL and parse_str() turns it into an array inside $_GET. The ?? "" avoids passing null when a URL has no query.
- Superglobals inside a function
$category = $_GET["category"] ?? "all";$_GET is visible inside the function with no global keyword, which is what makes it a superglobal. ?? "all" supplies a default instead of a warning when the key is missing.
- Convert the type
$page = (int) ($_GET["page"] ?? 1);A query-string value is the string "2", so (int) converts it. A cast converts without checking, though, so the next lesson uses filter_var for a safer check.
SAPI: cli
GET parameters: 0
Has REQUEST_METHOD: no
GET category=books page=2Which $_SERVER keys can you trust?
$_SERVER holds many keys of differing trustworthiness. REQUEST_METHOD, REQUEST_URI and QUERY_STRING come from the request line, but the contents of the URI are chosen by the visitor. Every key starting with HTTP_ (HTTP_HOST, HTTP_USER_AGENT, HTTP_REFERER) comes from request headers and is fully client-controlled. REMOTE_ADDR comes from the TCP connection, but behind a reverse proxy it shows the proxy's address. PHP_SELF can include extra path text a visitor appends after the script name on many setups, so printing it into HTML can lead to XSS.
<?php
function safeHost(array $server, array $allowed): string
{
$host = strtolower((string) ($server["HTTP_HOST"] ?? ""));
$host = (string) preg_replace('/:\d+$/', "", $host); // drop a :port suffix
return in_array($host, $allowed, true) ? $host : $allowed[0];
}
$allowed = ["shop.example.com", "www.example.com"];
echo safeHost(["HTTP_HOST" => "WWW.Example.com:8080"], $allowed), "\n";
echo safeHost(["HTTP_HOST" => "evil.test"], $allowed), "\n";
echo safeHost([], $allowed), "\n";This function lowercases the Host header, strips the port, and accepts it only if it appears in an allowlist you defined in advance. The output is www.example.com, shop.example.com and shop.example.com: both evil.test and the missing header fall back to the first allowlist entry. For important URLs such as password reset links, it is better to build them from a fixed domain in your configuration than from HTTP_HOST.
Reading raw superglobals once, at the edge
The queryValue() function below never touches a superglobal; it reads only its array parameter. If the value is not a string (an array such as ?q[]=a&q[]=b), or if it is present but empty as in ?q=, it returns the default. ?? only catches a missing key, not a key that exists with an empty value, which is why is_string() and trim() do the checking here.
<?php
function queryValue(array $get, string $key, string $default = ""): string
{
$value = $get[$key] ?? "";
if (!is_string($value) || trim($value) === "") {
return $default;
}
return trim($value);
}
$requests = ["?q=%20php%20&page=2", "?q[]=a&q[]=b&page=3", "?q=&page=", ""];
foreach ($requests as $query) {
parse_str(ltrim($query, "?"), $get);
$label = $query === "" ? "(empty)" : $query;
echo str_pad($label, 20), " q=", queryValue($get, "q", "none"),
" page=", queryValue($get, "page", "1"), "\n";
}The output: ?q=%20php%20&page=2 gives q=php page=2 (spaces trimmed), the array request gives q=none page=3, ?q=&page= gives q=none page=1, and the empty request gives q=none page=1. A function written this way can be tested with plain arrays and no browser, and you can state exactly what type each value has.
In real projects
Where this shows up in real projects
Real applications read superglobals in one place only. The front controller (index.php) reads REQUEST_METHOD and REQUEST_URI and hands off to a router. Frameworks such as Laravel and Symfony wrap the superglobals in a Request object, so application code never touches $_GET directly, and tests can build a Request by hand with no web server. In small projects of your own you can follow the same idea with functions like handle(array $get, array $post): string.
Production adds details to watch. Behind a reverse proxy, REMOTE_ADDR is the proxy's address, and the X-Forwarded-For header can be trusted only when your own proxy sets it, otherwise a visitor can fake it. Checking $_SERVER["HTTPS"] for HTTPS may also be wrong behind a proxy. Never keep important values such as a role or a price in $_COOKIE; keep them server-side in the session.
Common mistakes
Common mistakes
1. Reading a key without planning for it to be missing
Reading $_GET["name"] without ?? prints Warning: Undefined array key "name" when the request has no name, and the value behaves like null. Write $_GET["name"] ?? "" or test with isset().
2. Assuming the value is always a string
With ?tag[]=a&tag[]=b, $_GET["tag"] is an array. trim($_GET["tag"]) throws TypeError: trim(): Argument #1 ($string) must be of type string, array given, while an (int) cast turns the array into 1 and hides the problem. Check with is_string() first.
3. Printing $_SERVER["PHP_SELF"] straight into HTML
In <form action="<?= $_SERVER['PHP_SELF'] ?>">, a URL such as /form.php/"><script>... can end up inside PHP_SELF on some server setups and break out of the HTML. Use action="" (the current URL) or a fixed path instead.
4. Trusting a cookie that stores a role or price
A check such as $_COOKIE["isAdmin"] === "1" can be bypassed by anyone who edits the cookie in the browser's developer tools. Keep authorization data in a server-side session or database and put only the session ID in the cookie.
Best practices
Best practices
- Read superglobals in one place at the edge of the flow and pass only the selected fields on as parameters.
- Give every value a default with ?? and check its type with is_string() or filter_var().
- Avoid $_REQUEST and use the array that clearly matches GET or POST.
- When experimenting in the CLI, assign $_GET, $_POST and $_SERVER yourself, and test your functions with array parameters.
Mini challenge
Mini challenge: a request summary function
Write a summarize() function that does not read $_SERVER or $_GET directly but takes two array parameters. Simulate one request at the top of the script and call the function three times.
- summarize(array $server, array $get): string returns a string like "GET /shop.php q=php"
- Uppercase the method (default GET) and take the path with parse_url(..., PHP_URL_PATH) (default /)
- Trim q, and show (none) when it is missing, empty or an array
- Make the first call with a $_GET filled from $_SERVER["REQUEST_URI"] using parse_str()
<?php
function summarize(array $server, array $get): string
{
// TODO: method from $server (default GET, uppercase)
// TODO: path from REQUEST_URI with parse_url (default "/")
// TODO: q from $get: only a non-empty string counts, otherwise "(none)"
return "";
}
// TODO: set REQUEST_METHOD and REQUEST_URI on $_SERVER, fill $_GET with parse_str
// TODO: print summarize($_SERVER, $_GET), summarize([], []) and a POST case
// whose q is an arrayExpected: Expected output: GET /shop.php q=php GET / q=(none) POST /search q=(none)
Show hint
parse_url() can return null when there is no path, so fall back with ?: "/". After reading $get["q"], use is_string() to rule out arrays, trim it and test for an empty string. You can fill $_GET with parse_str(parse_url($uri, PHP_URL_QUERY) ?? "", $_GET).
Show solution
<?php
function summarize(array $server, array $get): string
{
$method = strtoupper((string) ($server["REQUEST_METHOD"] ?? "GET"));
$uri = (string) ($server["REQUEST_URI"] ?? "/");
$path = parse_url($uri, PHP_URL_PATH) ?: "/";
$q = $get["q"] ?? "";
$term = is_string($q) && trim($q) !== "" ? trim($q) : "(none)";
return "$method $path q=$term";
}
$_SERVER["REQUEST_METHOD"] = "get";
$_SERVER["REQUEST_URI"] = "/shop.php?q=php&page=2";
parse_str(parse_url($_SERVER["REQUEST_URI"], PHP_URL_QUERY) ?? "", $_GET);
echo summarize($_SERVER, $_GET), "\n";
echo summarize([], []), "\n";
echo summarize(["REQUEST_METHOD" => "POST", "REQUEST_URI" => "/search"],
["q" => ["a", "b"]]), "\n";Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Superglobals are ordinary arrays PHP fills for each request, and they are visible inside functions without the global keyword.
- The CLI has no request, so $_GET, $_POST and $_COOKIE are empty; assign $_GET and $_SERVER to simulate one.
- $_GET, $_POST, $_COOKIE and HTTP_* keys are chosen by the visitor and are untrusted; a value may be a string or an array.
- Read raw superglobals once at the edge and pass cleaned fields into functions as parameters.
PHP Security Manual — PHP Documentation Group