我开发了一个名为PHP-Bouncer的库,我认为它可以很好地满足您的需求。它目前支持完全托管的访问,这将允许您在每个页面上使用单个调用(我当然建议使用包含)并在人们无权访问页面时自动重定向,以及自动检索角色一个数据库(如果您使用包含的 MySQL 表设置脚本在数据库中实现角色)。语法非常简单。
您创建保镖:
$bouncer = new Bouncer();
添加您的角色(手动):
// Add a role Name, Array of pages role provides
$bouncer->addRole("Public", array("index.php", "about.php", "fail.php"));
// Add a role Name, Array of pages role provides
$bouncer->addRole("Registered User", array("myaccount.php", "editaccount.php", "viewusers.php"));
// Add a role Name, Array of pages role provides List of pages that are overridden by other pages
$bouncer->addRole("Admin", array("stats.php", "manageusers.php"), array("viewusers.php" => "manageusers.php"));
或从数据库:
// conf_* values are set in a config file, or you can pass them in explicitly
$bouncer->readRolesFromDatabase(conf_hostname, conf_username, conf_password, conf_schema, "mysql");
添加一个用户并给他们一些角色(注意:有一个名为 BouncerUser 的类,您的 User 类可以扩展它,它提供了您需要的所有角色功能!):
$user->addRole("Logged In"); // This Role doesn't exist in the bouncer, but we can set it anyways if we feel like setting another flag on the user's account. This can be useful for displaying content in a page only if a user has a secondary role.
$user->addRole("Public");
$user->addRole("Registered User");
然后让 Bouncer 管理对您文件的访问:
$bouncer->manageAccess($user->getRoles(), substr($_SERVER["PHP_SELF"], 1), "fail.php");
// Any time the user tries to go to a page they don't have access to, they will get to
// fail.php. Any time they try to go to a page that is overridden for them, they will
// get to the overriding page.
如果您只想在用户有权查看的情况下在页面中显示内容,只需将其包装在:
if($user->hasRole("Registered User")){
echo "The content";
}
我认为对于您描述的问题,这将是一个很好的解决方案!