PHP.GT

ProtectedGlobal documentation

phpgt/protectedglobal helps us stop accidental use of PHP superglobals in the parts of an application where we want stronger encapsulation.

In plain PHP, arrays such as $_GET, $_POST, $_COOKIE, and $_SERVER are available everywhere. That can be convenient in very small scripts, but in larger systems it makes data flow hard to follow. Any part of the codebase can read from, write to, or unset global request data without making that dependency obvious.

This library replaces selected superglobals with GT\ProtectedGlobal\ProtectedGlobal objects. Those objects allow access only to explicitly whitelisted offsets. Any other array access throws a ProtectedGlobalException, making accidental global usage obvious during development.

[!TIP] This library pairs naturally with PHP.GT/Input. Input gives us an object-oriented way to read request data, while ProtectedGlobal helps catch code that still reaches for the raw superglobals.

[!NOTE] WebEngine uses this library during application start-up to protect the common request-related superglobals before page logic runs. That helps keep page logic focused on injected services such as Input and Request rather than hidden global state.

What this library does

  • Wraps selected superglobal arrays in protective objects.
  • Allows a whitelist of offsets to remain accessible where needed.
  • Throws a dedicated exception when blocked global access is attempted.
  • Leaves clear debug output behind when a protected global is dumped accidentally.

A small example

use GT\ProtectedGlobal\Protection;

$protection = new Protection();

$whitelist = $protection->removeGlobals(
	[
		"_GET" => $_GET,
		"_POST" => $_POST,
		"_COOKIE" => $_COOKIE,
	],
	[
		"_COOKIE" => ["XDEBUG_SESSION"],
	]
);

$protection->overrideInternals($whitelist);

// Allowed because it was whitelisted.
$xdebugSession = $_COOKIE["XDEBUG_SESSION"];

// Throws GT\ProtectedGlobal\ProtectedGlobalException.
$page = $_GET["page"];

In practice, that means we can move request handling into explicit objects and services, while still leaving a narrow escape hatch for the few offsets that genuinely need to stay available.


Start with the Quick start guide to see the normal setup sequence.