iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP Superglobals

Superglobals are arrays PHP populates automatically — request data, server info, cookies, sessions. Available in every scope without global.

The set

VariableHolds
$_GETQuery-string params from the URL.
$_POSTForm fields from a POST request.
$_REQUESTGET + POST + COOKIE merged (avoid; ambiguous).
$_FILESUploaded files (with multipart forms).
$_COOKIECookies sent by the browser.
$_SESSIONPer-user session store (after session_start()).
$_SERVERRequest info: URL, headers, IP, user agent.
$_ENVEnvironment variables.
$GLOBALSAll globals merged into one array.

Reading request input safely

PHP
$name  = trim($_POST['name']  ?? '');
$page  = (int) ($_GET['page']  ?? 1);
$theme = $_COOKIE['theme'] ?? 'light';

Handy $_SERVER keys

KeyValue
REQUEST_METHOD'GET', 'POST', …
REQUEST_URI'/users/42?tab=orders'
HTTP_HOST'example.com'
HTTPS'on' if TLS; empty otherwise
REMOTE_ADDRClient IP
HTTP_USER_AGENTBrowser UA string
HTTP_REFERERPrevious page (untrustworthy)

Treat them as untrusted

Every superglobal except $_SESSION contains data from the user. Validate. Sanitise. Never interpolate straight into SQL or HTML.

Tip: Modern frameworks (Laravel, Symfony) wrap these in a Request object with typed accessors and validation. New code: prefer the framework's Request over poking superglobals directly.

Example

Example
<?php
// Available everywhere — superglobals.
print_r($_SERVER);
print_r($_GET);
print_r($_POST);
print_r($_COOKIE);
print_r($_SESSION ?? []);
print_r($_ENV);
Try it Yourself »

Exercise

Read a query-string parameter from…

$ _['page']

Test yourself

Q1. $_GET holds…
Q2. Session data lives in…
Q3. Should you trust $_SERVER["HTTP_USER_AGENT"]…

Discussion

Loading…