PHP superglobals expose request, upload, cookie, session, environment, server, and global-process values in every scope, but keys and availability vary by SAPI and configuration and most request-derived values are untrusted.
Safe applications read them once at an adapter, validate exact shape and limits, configure proxy and session trust, protect secrets, avoid ambiguous REQUEST and GLOBALS access, and pass typed values into core code.
| Array | Contains | Trust boundary |
|---|---|---|
| $_GET | Query-string values | Client controlled |
| $_POST | Parsed form body values | Client controlled |
| $_COOKIE | Cookies returned by the browser | Client controlled |
| $_FILES | Upload metadata and temporary paths | Client controlled metadata |
| $_SERVER | Request and server context | Some values can reflect client headers |
| $_SESSION | Server-side session data | Application controlled after session_start() |
| $_ENV | Environment values exposed by configuration | Deployment controlled |
Use ?? for an optional value, then validate according to the intended domain. Do not rely on FILTER_DEFAULT for validation because it leaves input unchanged.
<?php
$page = filter_input(
INPUT_GET,
'page',
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]
);
$page = $page === false || $page === null ? 1 : $page;
echo "Page {$page}";
Page 1
The fallback covers both a missing value and failed validation.
$_SERVER[\"REQUEST_METHOD\"] is useful for routing form behavior. HTTP header values can be supplied by clients, so do not treat values such as HTTP_USER_AGENT as proof of identity.
Use framework or trusted proxy configuration to determine client IP and scheme when the application runs behind a reverse proxy.
<?php
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
http_response_code(405);
header('Allow: POST');
exit('Method Not Allowed');
}
Check the upload error code, size, and detected MIME type. Generate a server-side file name and move the temporary file with move_uploaded_file(). Never trust the original file name as a storage path.
PHP superglobals are arrays available in every scope: `$GLOBALS`, `$_SERVER`, `$_GET`, `$_POST`, `$_FILES`, `$_COOKIE`, `$_SESSION`, `$_REQUEST`, and `$_ENV`. Availability and individual keys can depend on configuration, server interface, request type, and runtime mode.
Global availability is convenience, not trust. Query parameters, form fields, cookies, headers, upload metadata, and many server values can be controlled by a client. Environment and session values have different owners but still need presence and type checks.
Read superglobals at a request or command adapter, validate them, and pass typed values inward. Direct reads inside domain services hide dependencies and make tests depend on ambient process state.
Do not replace or mutate global arrays as a normalization strategy. Build an immutable request command or value map so later code cannot confuse raw and trusted values.
`$_GET` contains parsed query-string values and is suitable for filters, search, sorting, and pagination, not because it is safe but because those operations describe retrieval. Repeated and bracketed names can create arrays rather than strings.
`$_POST` contains parsed form values for supported POST media types. It does not automatically contain an arbitrary JSON body; read and bound the request stream for JSON. POST data is no more trustworthy than GET data.
Validate expected scalar or array shape before casting. A cast can turn a malicious array into warnings or an unintended value. Distinguish missing, empty, zero, false, and invalid values according to the field contract.
`filter_input` reads the original SAPI input while `filter_var` validates a value already read or normalized. Choose validation filters as syntax checks and add domain rules for ranges, ownership, allowed identifiers, and cross-field relationships.
`$_SERVER` mixes web-server, execution, path, method, timing, and request-header data. The manual does not guarantee every server provides every key, and many web-specific values are absent or meaningless in CLI execution.
Keys prefixed with `HTTP_` normally originate from client headers and are untrusted. Host, forwarding, scheme, and client-IP values require an explicit trusted-proxy configuration; accepting any forwarded header lets clients spoof security and audit context.
Use `REQUEST_METHOD` for routing only after a default or missing-key policy. Build URLs from configured canonical origins rather than a client-supplied Host header when links affect security, password reset, or redirects.
Request timing values help elapsed-time diagnostics, while script and filesystem fields can reveal physical paths. Keep server arrays out of public dumps and redact them from exception pages and support exports.
`$_COOKIE` contains client-supplied cookie values. A cookie name, value, expiry, or UI visibility does not prove integrity or authorization. Verify signed values or look up opaque identifiers in trusted server storage.
`$_SESSION` becomes available after session startup and represents server-managed session state keyed by a client session identifier. Regenerate identifiers at authentication privilege changes and configure secure cookie attributes and expiry policy.
Store minimal stable identity and workflow state in the session rather than full mutable domain objects. Large or stale session data increases locking, migration, and revocation complexity.
Close session writing before long streaming or remote work when supported by the application flow so concurrent requests from the same session are not unnecessarily blocked. Revalidate authorization against current server data for important actions.
`$_FILES` describes multipart uploads with nested name, type, temporary path, error, and size fields. Check the upload error code first, validate expected structure, enforce limits, inspect content, and move only confirmed uploaded files.
Original filenames and client MIME types are display metadata, not storage paths or security evidence. Generate storage names and keep writable uploads outside executable source directories.
`$_ENV` availability depends on PHP configuration and process setup. Environment values are strings and may be missing; parse booleans, numbers, lists, and URLs under an explicit startup schema instead of using loose truthiness.
Environment variables can carry secrets but are not automatically safe to print, inherit into child processes, or expose in diagnostic pages. Redact them and fail startup clearly when required configuration is absent.
`$_REQUEST` can combine GET, POST, and cookie data according to configuration, making value precedence and trust source unclear. Prefer the specific superglobal that matches the route contract so a cookie cannot unexpectedly replace a query or form field.
`$GLOBALS` references variables in global scope and allows indirect global mutation. Application code should pass dependencies and state explicitly; a global registry makes construction order, ownership, and tests difficult to reason about.
The CLI variables `$argc` and `$argv` are predefined command inputs rather than members of the superglobal list in every context. Parse command arguments through a declared option grammar and never interpolate them into shell or SQL commands.
Native request adapters or framework request objects can provide a cleaner interface, but they do not create trust. Keep the same shape, size, validation, authorization, and encoding rules after abstraction.
Test missing keys, scalar-versus-array attacks, repeated parameters, empty and falsy values, invalid encoding, excessive nesting, oversized fields, spoofed forwarding headers, stale sessions, malformed uploads, and absent environment configuration.
Use integration tests through the real web server or framework request path for parsing behavior, then unit-test the adapter with explicit arrays. Restore changed superglobals after isolated tests so one case cannot contaminate another.
Assert that validation failures produce no persistence, file, or remote side effects. Response tests should verify safe error messages and output encoding without echoing raw server or environment state.
At deployment, verify `variables_order`, upload and body limits, session settings, proxy trust, environment schema, and web-versus-CLI differences. Configuration is part of the boundary contract and belongs in release checks.
0 of 2 checked
Try this next
0 of 2 completed
Explore 500+ free tutorials across 20+ languages and frameworks.