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";