What Are Superglobals?

Yo Yogesh.M Updated 01 Nov 2026
6 min read ·Lesson 212 of 219

In simple terms: Superglobals are built-in PHP variables that contain information about the current request — the URL parameters, submitted form data, uploaded files, cookies, session data, and server details. They are available everywhere in your code without any special declaration. Technically: Superglobals are predefined arrays that PHP populates automatically at the start of each request. Unlike ordinary variables, they are accessible in every scope — global code, functions, and class methods — without the global keyword.

Why They Exist

A web application must react to what the visitor sends: which page was requested, what was typed into a form, which file was uploaded, which cookies the browser stored. PHP collects all of this from the HTTP request and the server environment and places it into superglobal arrays before your script starts running.


The Nine Superglobals

SuperglobalContainsFilled FromLesson
$_GETURL query parametersThe query string (?page=2&sort=price)$_GET
$_POSTForm data sent with POSTThe request body (form-encoded or multipart)$_POST
$_FILESUploaded filesMultipart form uploads$_FILES
$_COOKIECookies sent by the browserThe Cookie request header$_COOKIE
$_SESSIONData stored for the current user's sessionServer-side session storage (after session_start())$_SESSION
$_REQUESTA combination of GET, POST (and possibly cookie) dataBuilt from the above, depending on configuration$_REQUEST
$_SERVERRequest and server informationThe web server and PHP environment$_SERVER
$_ENVEnvironment variablesThe process environment (if enabled)$_ENV
$GLOBALSAll variables in the global scopeYour script's global variables$GLOBALS

Superglobals Are Available in Every Scope

Ordinary global variables are not visible inside functions (see Variables Scope). Superglobals are:

<?php
// Request: GET /search.php?q=php+arrays&page=2
function currentSearchTerm(): string
{
    return trim($_GET['q'] ?? '');
}
function currentPage(): int
{
    return max(1, (int) ($_GET['page'] ?? 1));
}
echo "Searching for: " . htmlspecialchars(currentSearchTerm()) . "\n";
echo "Page: " . currentPage() . "\n";

Output

Searching for: php arrays
Page: 2

Both functions read $_GET directly, without parameters or global. In the query string, + represents a space, and PHP decodes it automatically when filling $_GET.

Design note: Being able to read superglobals anywhere is convenient, but it hides where a function's data comes from and makes the function hard to test. A cleaner design reads request data once — at the "edge" of the application (for example, in a controller) — and passes the validated values to other functions as parameters.


How a Request Fills the Superglobals

Consider a form submission:

POST /contact.php?source=footer HTTP/1.1
Host: gocourse.in
Content-Type: application/x-www-form-urlencoded
Cookie: theme=dark
name=Asha&email=asha%40example.com&message=Hello

PHP fills the superglobals like this:

SuperglobalContents
$_GET['source' => 'footer']
$_POST['name' => 'Asha', 'email' => 'asha@example.com', 'message' => 'Hello']
$_COOKIE['theme' => 'dark']
$_SERVER['REQUEST_METHOD']'POST'
$_SERVER['REQUEST_URI']'/contact.php?source=footer'
$_SERVER['HTTP_HOST']'gocourse.in'

A request can contain query parameters and a body at the same time, so $_GET and $_POST can both have data. Values are URL-decoded automatically (%40 becomes @).


All Input Is Untrusted

Everything in $_GET, $_POST, $_COOKIE, $_FILES, $_REQUEST, and most of $_SERVER comes from the client. Users — and attackers — can send any value, regardless of what your HTML form allows:

  • Hidden fields and dropdowns can be changed in the browser's developer tools.

  • Requests can be sent with tools such as curl without any form at all.

  • Headers such as User-Agent, Referer, and Host can contain anything. This leads to three essential rules:

  1. Validate every input: check type, format, length, and allowed values.
  2. Escape every output for its context: htmlspecialchars() for HTML, prepared statements for SQL.
  3. Never trust client data for security decisions (prices, user IDs, permissions) — look them up on the server.

Example: Validating Input

<?php
// Request: GET /products.php?category=books&page=abc&sort=price_desc
$allowedSorts = ['newest', 'price_asc', 'price_desc'];
$category = preg_match('/^[a-z-]{1,30}$/', $_GET['category'] ?? '') ? $_GET['category'] : 'all';
$page = filter_var($_GET['page'] ?? 1, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) ?: 1;
$sort = in_array($_GET['sort'] ?? '', $allowedSorts, true) ? $_GET['sort'] : 'newest';
echo "Category: $category, page: $page, sort: $sort\n";

Output

Category: books, page: 1, sort: price_desc
  • category must match a simple pattern (lowercase letters and hyphens).
  • page must be a positive integer; 'abc' is rejected and replaced with 1.
  • sort must be one of the allowed values. Validation is covered in depth in the PHP Forms section.

Values Are Strings (or Arrays of Strings)

Data from $_GET, $_POST, and $_COOKIE always arrives as strings — even numbers. A parameter written with brackets in its name arrives as an array:

<?php
// Request: GET /filter.php?min=500&tags[]=new&tags[]=sale
var_dump($_GET['min']);
var_dump($_GET['tags']);

Output

string(3) "500"
array(2) {
  [0]=>
  string(3) "new"
  [1]=>
  string(4) "sale"
}

Because a parameter can be a string or an array, code that expects a string must check its type. Passing an unexpected array to string functions causes a TypeError (see $_GET).


Superglobals in the Command Line

When a script runs from the command line (php script.php), there is no HTTP request:

  • $_GET, $_POST, $_COOKIE, and $_FILES are empty arrays.
  • $_SERVER['argv'] contains the command-line arguments, and $_SERVER['argc'] their count.
<?php
// Run: php report.php 2026-10 csv
echo "Script: {$_SERVER['argv'][0]}\n";
echo "Month: " . ($_SERVER['argv'][1] ?? 'current') . "\n";
echo "Format: " . ($_SERVER['argv'][2] ?? 'txt') . "\n";

Output

Script: report.php
Month: 2026-10
Format: csv

See PHP Command Line (CLI).


Configuration That Affects Superglobals

php.ini SettingEffect
variables_orderWhich superglobals are populated ("GPCS" in the recommended php.ini files; E is omitted, so $_ENV is usually empty — use getenv() instead)
request_orderWhich data $_REQUEST combines, and in which order ("GP" in the recommended files)
post_max_sizeMaximum size of a POST body; if exceeded, $_POST and $_FILES are empty
max_input_varsMaximum number of input variables (default 1000); extra fields are dropped with a warning
upload_max_filesizeMaximum size of each uploaded file

Superglobals in Frameworks

Frameworks wrap superglobals in request objects — for example, $request->query('page') in Laravel or $request->query->get('page') in Symfony. These objects make code testable (a fake request can be passed in) and provide helpers for validation. Understanding the raw superglobals explains what these objects do internally.


Common Mistakes

Reading Input Without Defaults

Effect: "Undefined array key" warnings when a parameter is missing. Fix: $_GET['page'] ?? 1.

Printing Input Without Escaping

Effect: Cross-site scripting (XSS). Fix: htmlspecialchars($_GET['q'] ?? '').

Using Input Directly in SQL

Effect: SQL injection. Fix: Prepared statements (see PDO Prepared Statements).

Trusting Client-Supplied Values

Effect: Users manipulate prices, IDs, or roles. Fix: Recalculate and authorize everything on the server.

Modifying Superglobals

Effect: Other parts of the application see changed "input", which is confusing and hard to debug. Fix: Copy values into variables, validate them, and work with those.


Best Practices

  • Read request data at the edge of your application, validate it, and pass clean values onward.
  • Use ?? defaults for optional parameters.
  • Validate with filter_var(), allow-lists, and patterns; escape all output.
  • Prefer $_GET and $_POST over $_REQUEST so the data source is explicit.
  • Treat superglobals as read-only. Official reference: https://www.php.net/manual/en/language.variables.superglobals.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings Function Arguments PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer PHP Form Handling PHP XML Parsers PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro PHP Class Constants Encryption with Sodium Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions array_map / array_filter / array_reduce Array Functions What Are Superglobals? $GLOBALS What Is `$_SERVER` ? $_REQUEST $_POST $_GET $_FILES $_COOKIE
Ask about this post
AI Ask about this post

Ask questions about What Are Superglobals? and get answers drawn from it.

Signed-in readers only.