我有一个PHP网站,有多个PHP脚本.我需要从另一个站点向用户提供有限访问权限的用户.我想限制这些ppl可以访问的页面.
我这样做的方式如下:
// $_SESSION['systemid'] is set with a value of say, '1'
$permissionArray = $objACCESS->getPermissions($_SESSION['systemid']);
// getPermissions returns an array like the following (for that systemid):
// 0 => {'systemid' => '1', 'permission_type' => 'createcontent' }
// 1 => {'systemid' => '1', 'permission_type' => 'invitecontacts' }
// the following contain a list of script names that should be
// restricted if permission is not allowed
$createcontent = array('createcontent.php');
$managecontent = array('managecontent.php');
$invitecontacts = array('invitecontacts.php');
$page_name=basename($_SERVER["SCRIPT_FILENAME"]);
if(is_array($permissionarray))
{
$haspermissions = false;
foreach($permissionarray as $permissions)
{
if(in_array($page_name,${"$permissions[permission_type]"}))
{
$haspermissions = true;
break;
}
}
}
if($haspermissions==false)
{
// - do not have permissions
echo "<meta http-equiv=\"refresh\" content=\"0;url=".$site_url."404.php\">";
die;
}
...
// rest of the code
...
Run Code Online (Sandbox Code Playgroud)
Q1:有更好的方法来限制用户访问吗?
Q2:如果没有,有没有办法让这种方法更有效/最佳?
这里的底层身份验证机制对我来说没有意义。$_SESSION['systemid'] 是如何设置的?什么是“系统”?
不管怎样,我假设你已经解决了这部分问题。因此,我将编辑您上面的内容,如下所示:
首先,调整 getPermissions 以返回类似以下内容:
$perms = array(
'createcontact' => 1,
'invitecontacts' => 1
);
Run Code Online (Sandbox Code Playgroud)
该数组只会填充与该“系统”关联的权限。
然后,检查当前“系统”是否具有页面所需的权限,如下所示:
$cur_page_perm_key = basename($_SERVER['SCRIPT_FILENAME'], '.php');
$has_permission = isset($perms[$cur_page_perm_key]);
if(!$has_permission) {
// No permission? Redirect to an unauthorized page
header('HTTP/1.0 401 Not Authorized');
header('Status: 401 Not Authorized');
header('Location: /unauthorized.php');
exit;
}
Run Code Online (Sandbox Code Playgroud)
简单的“isset”检查将比循环快得多,特别是在权限/页面数量增加的情况下。
希望这有帮助。