Skip to content
Tutorials Center
My learning

Topics

Lesson 73 of 147 ยท PHP and the Web

Superglobals

Understand PHP superglobals - $_GET, $_POST, $_SERVER, $_FILES, $_COOKIE, $_SESSION, $_ENV and why to avoid $_REQUEST - with simulated web requests you can run.

When a browser asks your server for a page, the request carries a lot of information: the URL and its query string, form fields, cookies, uploaded files, and headers like the browser's preferred language. PHP unpacks all of that before your script starts and puts it into a handful of predefined arrays called superglobals. They're named $_GET, $_POST, $_SERVER, $_COOKIE, $_FILES, $_SESSION, $_REQUEST and $_ENV, plus $GLOBALS.

"Super" refers to their scope: unlike normal variables, superglobals are visible everywhere, inside every function and method, without the global keyword you met in Variable Scope. That convenience is also their danger. Everything in them (except $_SESSION and $_ENV) comes straight from the client, so every value is untrusted input that an attacker can set to anything.

This lesson explains what each superglobal holds and how to read it safely. Our editor runs PHP on the command line, where there is no web request, so the runnable examples simulate one by filling the arrays at the top of the script, exactly as a web server would. The code that reads them is the same code you'd write for a real site.

The superglobals at a glance

Superglobal Contains Comes from
$_GET Query string parameters (?page=2&sort=name) The URL
$_POST Form fields sent in the request body The browser (form submission)
$_SERVER Request details and server environment: method, URI, headers, IP The web server and the request
$_COOKIE Cookies the browser sent The Cookie request header
$_FILES Information about uploaded files A multipart/form-data form
$_SESSION Your own per-visitor data stored on the server Your code (after session_start())
$_REQUEST $_GET + $_POST (+ $_COOKIE, depending on config) merged All of the above
$_ENV Environment variables (often empty in production) The process environment
$GLOBALS All global variables Your script

Superglobals are visible inside functions without any declaration:

PHP Superglobals are visible everywhere

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP_SAPI is cli in our editor. On a web server it would be something like fpm-fcgi or apache2handler (see How PHP Works).

$_GET: the query string

Everything after the ? in a URL is the query string: name=value pairs separated by &. PHP decodes it into $_GET. A link to /search.php?q=red+shoes&page=2 gives:

PHP
$_GET = ['q' => 'red shoes', 'page' => '2'];

Three facts matter whenever you read $_GET:

  1. Any key can be missing. Users edit URLs, bots strip them, old links lack new parameters. Reading a missing key prints Warning: Undefined array key, so always use ?? with a default or check with isset().
  2. Every value is a string (or an array, see below), even page=2. Validate and convert it before use; Handling Forms shows filter_var() for that.
  3. Square brackets in names create arrays. ?tag[]=php&tag[]=web gives $_GET['tag'] === ['php', 'web'], and ?filter[color]=red gives a nested array. An attacker can send an array where you expect a string, so check the type.

PHP's own parser is available as parse_str(), which this simulation uses to turn a URL into $_GET the same way the server does:

PHP Reading the query string safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The var_dump() shows that + and %20 were decoded into spaces and that page is the string "2". When you create links, use http_build_query() (or urlencode() for a single value) instead of gluing strings together, so special characters like & and spaces are encoded properly.

Query strings appear in browser history, server logs, analytics tools and the Referer header sent to other sites. Never put passwords, tokens or personal data in a URL. Use $_GET for things that are fine to bookmark and share: search terms, filters, page numbers.

$_POST: form data in the request body

When an HTML form uses method="post", the browser sends the fields in the request body instead of the URL, and PHP decodes them into $_POST:

HTML
<form method="post" action="/subscribe.php">
  <input name="email" type="email">
  <input name="topics[]" type="checkbox" value="php" checked>
  <input name="topics[]" type="checkbox" value="sql">
  <button>Subscribe</button>
</form>

The same rules apply as for $_GET: keys may be missing (an unchecked checkbox sends nothing at all), values are strings, and bracketed names become arrays. Check $_SERVER['REQUEST_METHOD'] to tell whether the page is being displayed (GET) or a form was submitted (POST):

PHP Handling a simulated POST request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

$_POST is only filled for form encodings (application/x-www-form-urlencoded and multipart/form-data). A request with a JSON body leaves $_POST empty; you read the raw body from php://input instead (see Streams and Wrappers and Building a JSON API).

$_SERVER: about the request and the server

$_SERVER holds information from the web server: the request method, the path, the client's IP address, whether HTTPS is used, the script's location, and every request header. Headers appear with an HTTP_ prefix, uppercased, with dashes turned into underscores: Accept-Language becomes $_SERVER['HTTP_ACCEPT_LANGUAGE'], and User-Agent becomes HTTP_USER_AGENT.

Key Example Meaning
REQUEST_METHOD POST HTTP method
REQUEST_URI /blog/post.php?id=4 Path plus query string, as requested
QUERY_STRING id=4 Just the query string
SCRIPT_NAME /blog/post.php URL path of the running script
SCRIPT_FILENAME /var/www/site/public/blog/post.php File system path of the script
DOCUMENT_ROOT /var/www/site/public The web root folder
HTTP_HOST example.com Host header (client-controlled!)
HTTPS on Set (non-empty) when the request used HTTPS
REMOTE_ADDR 203.0.113.7 IP address of the connecting client
HTTP_USER_AGENT Mozilla/5.0 ... Browser identification
REQUEST_TIME_FLOAT 1760781600.123 When the request started
PHP Reading request details from $_SERVER

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Values from headers are as untrusted as form fields: HTTP_HOST, HTTP_USER_AGENT, HTTP_REFERER and HTTP_X_FORWARDED_FOR are all written by the client. Don't build links from HTTP_HOST without checking it against a list of your domains, and escape REQUEST_URI and PHP_SELF before printing them. REMOTE_ADDR is set by the server, but behind a proxy or CDN it's the proxy's IP; frameworks read X-Forwarded-For only when the request really came through a proxy you trust.

These three get full lessons of their own, so here is just the shape of each:

  • $_COOKIE holds the cookies the browser sent: ['theme' => 'dark', 'PHPSESSID' => 'k3j...']. The browser can send any value it likes, so treat cookies like form input. Setting them is done with setcookie(), covered in Cookies.
  • $_FILES describes uploaded files. Each field has name, full_path, type, tmp_name, error and size keys; the file itself waits in a temporary location until you move it. See File Uploads.
  • $_SESSION is different from the rest: it's your data, stored on the server and linked to the visitor through a session cookie. It only exists after session_start(). See Sessions.

$_REQUEST: why to avoid it

$_REQUEST merges $_GET, $_POST and possibly $_COOKIE into one array. The order and the sources depend on the request_order and variables_order settings in php.ini (production configs usually use GP: GET first, then POST overwrites). That causes two problems:

  • You can't tell where a value came from. Code meant to accept a value only from a POST form will also accept it from a link, which makes attacks like CSRF easier.
  • A cookie or query parameter with the same name can silently replace the form field, depending on server configuration.
PHP Why $_REQUEST is ambiguous

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Read each value from the array it belongs to: $_GET for URL parameters, $_POST for form fields, $_COOKIE for cookies.

$_ENV, getenv() and $GLOBALS

Environment variables are how deployments pass configuration to an application: database passwords, API keys, the environment name (APP_ENV=production). PHP fills $_ENV with them only if the variables_order setting includes E. The recommended production php.ini uses GPCS, so $_ENV is often empty on real servers. getenv('NAME') reads the process environment directly and works regardless, returning false when the variable isn't set:

PHP Environment variables with getenv

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Frameworks usually load a .env file during development and put its values into the environment, so the same getenv() or env() call works locally and in production. Keep .env files out of version control and outside the web root.

$GLOBALS gives access to every global variable by name. Since PHP 8.1 it's a read-only copy as a whole (you can still change $GLOBALS['x'] = 1, but you can't replace or pass the entire array by reference). Reaching into globals from functions hides dependencies, so prefer passing values as parameters, as Variable Scope explains.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A visitor opens /list.php?page=2. What is var_dump($_GET['page']);?

    Request data always arrives as strings (or arrays). Convert and validate it, for example with filter_var() and FILTER_VALIDATE_INT.
  2. 2. How should you read an optional sort query parameter without risking an "Undefined array key" warning?

    The null coalescing operator returns the default when the key is missing, without any warning. $_REQUEST has the same missing-key problem and mixes sources.
  3. 3. Under which key does PHP put the browser's Accept-Language request header?

    Request headers are added to $SERVER with an HTTP prefix, uppercased, with dashes replaced by underscores.
  4. 4. Why is $_REQUEST best avoided?

    The merge order depends on configuration, and a value from a link or cookie can stand in for a POST field. Read from $_GET, $_POST or $_COOKIE explicitly.
  5. 5. A form posts JSON with Content-Type application/json. What does $_POST contain?

    PHP only decodes form encodings into $_POST. For JSON, read file_get_contents('php://input') and decode it with json_decode().

Summary

  • Superglobals are predefined arrays visible in every scope: $_GET, $_POST, $_SERVER, $_COOKIE, $_FILES, $_SESSION, $_REQUEST, $_ENV and $GLOBALS.
  • Request data is untrusted: keys may be missing (use ??), values are strings or arrays (validate and convert), and attackers control all of it.
  • $_GET holds query-string parameters; $_POST holds form fields from the request body (not JSON; use php://input).
  • $_SERVER describes the request (method, URI, HTTPS, client IP) and contains every header as HTTP_*; header values are client-controlled too.
  • Avoid $_REQUEST; read each value from the array it belongs to.
  • Use getenv() for configuration from environment variables, since $_ENV is often empty in production.
  • In the editor, requests are simulated by filling the arrays; on a server PHP fills them for you before your script starts.

Next: Handling Forms