phpgt / protectedglobal
防止意外使用超全局变量。
v1.1.1
2022-09-25 12:04 UTC
Requires
- php: >7.4
Requires (Dev)
- phpstan/phpstan: ^v1.8
- phpunit/phpunit: ^v9.5
This package is auto-updated.
Last update: 2024-09-10 14:16:31 UTC
README
默认情况下,PHP会将所有敏感用户信息通过超全局变量传递,这些变量在任意代码中都可以读取和修改,包括第三方库。这直接违反了面向对象编程的许多优点,并可能导致难以维护的代码。
假设已经建立了对超全局变量的面向对象抽象,这个库可以被用来将所有超全局变量替换为对象,这些对象会提醒开发者它们受保护和封装,同时可选地保留一个超全局变量白名单。
在静态 Protection
类中存在两个函数
removeGlobals
- 传入一个包含您希望清空的全球数组的数组。可以可选地传入一个要保留的键的白名单。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";