Skip to the workspace
Pebellslearn by building
HTTP Methods and Forms  ›  Capstone Project

$_REQUEST and $_SERVER

$_SERVER 13 min$_REQUEST merges GET, POST and possibly cookie values and hides where input came from, while $_SERVER describes the request, and its header-based values are written by the client and must be treated as untrusted.

php / $_REQUEST and $_SERVER

Explore each scene at your own pace.

01 · The rule

The rule

$_REQUEST and $_SERVER

$_REQUEST merges GET, POST and possibly cookie values and hides where input came from, while $_SERVER describes the request, and its header-based values are written by the client and must be treated as untrusted.

Inspect where request metadata comes from instead of treating all sources as interchangeable.

Pageturn's order script already reads $_POST and asks $_SERVER for the request method. PHP fills in a few more of these superglobals on every request. Two of them come up constantly: $_REQUEST, which is convenient and usually a mistake, and $_SERVER, which describes the request itself and deserves careful handling.

The rule

Read input from the source you expect; treat request details as claims.

$_REQUEST merges several sources into one array: $_GET, $_POST and, depending on configuration, cookies. When the same name appears in more than one, the server's request_order setting decides which one wins.

<?php
$qty = $_REQUEST['qty'] ?? 1;   // from the URL? the form? a cookie? unclear

That vagueness is the problem. An action that should only happen on a POST can be triggered by a plain link with ?qty=50, and a cookie can silently override a form field. Read $_GET or $_POST directly, so the code states where the data must come from.

$_SERVER holds information about the request and the environment:

Key Pageturn example
REQUEST_METHOD "POST"
REQUEST_URI "/search.php?q=dune"
QUERY_STRING "q=dune"
HTTP_HOST "pageturn.example"
HTTP_USER_AGENT the visitor's browser description
REMOTE_ADDR the IP address the connection came from
SCRIPT_NAME "/search.php"

The keys beginning with HTTP_ are copied from the request headers, and the client writes those headers. A script can send any User-Agent or Host it likes. So:

  • Use REQUEST_METHOD freely for branching; an unexpected value just fails your checks.
  • Treat HTTP_* values, REQUEST_URI and PHP_SELF as untrusted text: escape them before printing them into a page, and never use them to decide who someone is.
  • REMOTE_ADDR comes from the network connection, so it is harder to fake, but behind a proxy it is the proxy's address.

Some keys do not exist in every setup, for example when PHP runs from the command line, so read them with ?? too.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.