Tutorials Logic, IN info@tutorialslogic.com

PHP Superglobals: Request, Server, Session, and File Data

PHP Request Globals

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.

Superglobal Map

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

Query Input

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.

Validate a Page Number

Validate a Page Number
<?php
$page = filter_input(
    INPUT_GET,
    'page',
    FILTER_VALIDATE_INT,
    ['options' => ['min_range' => 1]]
);

$page = $page === false || $page === null ? 1 : $page;
echo "Page {$page}";
Output
Page 1

The fallback covers both a missing value and failed validation.

Server Context

$_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.

Require POST

Require POST
<?php
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
    http_response_code(405);
    header('Allow: POST');
    exit('Method Not Allowed');
}

Upload Metadata

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.

  • Confirm UPLOAD_ERR_OK before reading the temporary path.
  • Enforce a server-side size limit even when the form declares one.
  • Detect file type from content with Fileinfo when type matters.
  • Store uploads outside executable directories when possible.

Boundary Variables

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.

  • Expect missing keys and runtime-specific availability.
  • Assign trust according to each value source.
  • Convert ambient values at one adapter boundary.
  • Keep raw and validated data separate.

Query and Form Data

`$_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.

  • Treat query and form values as shape-variant input.
  • Read JSON separately from POST form parsing.
  • Validate before casting or indexing.
  • Apply domain rules after syntax filtering.

Server Metadata

`$_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.

  • Handle absent and CLI-specific server keys.
  • Trust forwarding headers only from configured proxies.
  • Build security-sensitive origins from configuration.
  • Do not expose raw server metadata publicly.

Cookies and Sessions

`$_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.

  • Treat cookie values as untrusted client input.
  • Regenerate sessions across privilege changes.
  • Keep session state small and version-tolerant.
  • Recheck current authorization for state changes.

Files and Environment

`$_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.

  • Validate the complete uploaded-file structure.
  • Ignore client filenames and MIME claims for security.
  • Parse environment strings into typed configuration.
  • Keep secrets out of dumps and child-process arguments.

Request and Globals

`$_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.

  • Avoid REQUEST when the source must be unambiguous.
  • Replace GLOBALS mutation with explicit dependencies.
  • Parse CLI arguments under a declared grammar.
  • Preserve trust checks behind request abstractions.

Boundary Tests

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.

  • Cover hostile shapes and missing runtime values.
  • Exercise the real request parser in integration tests.
  • Assert rejected input has no side effects.
  • Audit PHP and proxy configuration at deployment.
Before you move on

Mastery Check

5 checks
  • Read specific sources and expect absent or variant shapes.
  • Treat headers, query, form, cookie, and upload data as untrusted.
  • Configure proxy, session, upload, and environment boundaries.
  • Avoid REQUEST precedence and ambient GLOBALS mutation.
  • Test hostile inputs through real web and CLI paths.

Trust Boundary Check

0 of 2 checked

Q1. Is a value in $_COOKIE trusted because the server created it earlier?

Q2. What does FILTER_DEFAULT validate?

Try this next

Inspect One Request

0 of 2 completed

  1. Accept a positive integer page value and default missing or invalid input to 1.
  2. List every client-controlled value used by a sample form handler and state its validation rule.
Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.