PHP.GT

Quick start guide

In this guide we will protect the common request-related superglobals in a small PHP script.

The normal flow has two steps:

  1. collect the values we want to preserve
  2. replace the original globals with ProtectedGlobal objects

1. Install the package

composer require phpgt/protectedglobal

2. Create a Protection object

use GT\ProtectedGlobal\Protection;

$protection = new Protection();

Protection is the public entry point for the library.

3. Collect the globals we want to protect

$globals = [
	"_ENV" => $_ENV,
	"_SERVER" => $_SERVER,
	"_GET" => $_GET,
	"_POST" => $_POST,
	"_FILES" => $_FILES,
	"_COOKIE" => $_COOKIE,
	"_SESSION" => $_SESSION ?? [],
];

The keys should match the superglobal names that will later be overridden.

4. Optionally define a whitelist

If some offsets need to remain accessible, we can whitelist them before protection happens:

$whiteList = [
	"_COOKIE" => ["XDEBUG_SESSION"],
	"_ENV" => ["APP_ENV"],
];

We will look at this in more detail on Whitelisting superglobals.

5. Remove the allowed values from the originals

$allowed = $protection->removeGlobals($globals, $whiteList);

removeGlobals() returns a new array containing only the values that should remain readable after protection is enabled.

6. Override the real superglobals

$protection->overrideInternals($allowed);

After this point, accesses such as $_GET["page"] or $_POST["name"] will throw an exception unless those offsets were whitelisted.

7. Use explicit request objects instead of globals

Once the protection is in place, the rest of the application should prefer explicit abstractions.

For example, with PHP.GT/Input:

use GT\Input\Input;

$input = new Input(
	$globals["_GET"],
	$globals["_POST"],
	$globals["_FILES"]
);

Or in a framework such as WebEngine, use the injected request-related services instead of reading from the global arrays directly.

[!NOTE] ProtectedGlobal is designed to catch accidental global usage. It is not a validation library and it is not a replacement for request parsing by itself.


Next: Whitelisting superglobals