phpgt/protectedglobal

防止意外使用超全局变量。

v1.1.1 2022-09-25 12:04 UTC

README

默认情况下,PHP会将所有敏感用户信息通过超全局变量传递,这些变量在任意代码中都可以读取和修改,包括第三方库。这直接违反了面向对象编程的许多优点,并可能导致难以维护的代码。

假设已经建立了对超全局变量的面向对象抽象,这个库可以被用来将所有超全局变量替换为对象,这些对象会提醒开发者它们受保护和封装,同时可选地保留一个超全局变量白名单。

Build status Code quality Code coverage Current version PHP.Gt/ProtectedGlobal documentation

在静态 Protection 类中存在两个函数

  1. removeGlobals - 传入一个包含您希望清空的全球数组的数组。可以可选地传入一个要保留的键的白名单。
  2. overrideInternals - 传入所有超全局数组,用 ProtectedGlobal 类来覆盖。

示例用法

// Before protecting, abstract the globals using an OOP mechanism of choice.
$input = new Input($_GET, $_POST, $_FILES);
// etc...

Protection::removeGlobals([$_ENV, $_SERVER, $_GET, $_POST, $_FILES, $_COOKIE, $_SESSION], ["get" => ["xdebug"]]);
Protection::overrideInternals($_GLOBALS, $_ENV, $_SERVER, $_GET, $_POST, $_FILES, $_COOKIE, $_SESSION);

// Now an exception will be thrown when trying to access a global variable:
$_SESSION["god-object"] = "Value I want to pass around globally";