[英]PHP - Restrict access to admin page for logged on user
I have a table in my database for users, each user has an auth_level (1-3). 我的数据库中有一个用户表,每个用户都有一个auth_level(1-3)。 On my site I have a admin page for adding/deleting new user accounts, I want to restrict access to this page only to users that have an auth level of 3. I have been trying to get this to work with sessions but I am stuck. 在我的网站上,我有一个用于添加/删除新用户帐户的管理页面,我想限制只有具有3级身份验证级别的用户访问此页面。我一直试图让这个用于会话,但我被卡住了。 Hoping someone can help me out. 希望有人可以帮助我。
Here is my code for restricting access. 这是我的限制访问的代码。 Not sure where I have gone wrong. 不知道我哪里出错了。 the check.php start the session. check.php启动会话。
<?php
require_once('check.php');
//This function returns True if auth level = '3'
//Otherwise it returns False
function CheckAccess()
{
$result = (isset($_SESSION['SESS_AUTH_LEVEL']) && $_SESSION['SESS_AUTH_LEVEL'] == 3 );
if(!$result)
{
header('WWW-Authenticate: Basic realm=“Test restricted area”');
header('HTTP/1.0 401 Unauthorized');
return false;
}
else
{
header("location: admin.php");
}
}
?>
If I log in as a user with auth level 1 or 3, I get the same blank page. 如果我以身份验证级别为1或3的用户身份登录,则会获得相同的空白页面。
I think you never call CheckAccess()
. 我想你永远不会打电话给CheckAccess()
。 Calling it maybe fixes your error. 调用它可能会修复您的错误。
It's perfectly valid to do the following, which your function is doing. 执行以下操作完全有效,您的功能正在执行。
if (this=that) { /*do multiple*/ } else //do single;
However, it appears you are not calling this function? 但是,看来你没有调用这个功能? Try this: 尝试这个:
<?php
require_once('check.php');
CheckAccess();
?>
You are missing the closing }
of your function so all the if statement is seen as part of the method by PHP. 您缺少函数的结束}
因此所有if语句都被PHP视为方法的一部分。
Add a }
after $result =
and before if
在$result =
之后添加一个}
和之前的if
A slightly alternative version that should achieve what you want would be 一个稍微替代的版本,应该达到你想要的
<?php
function CheckAccess() {
$result = (isset($_SESSION['SESS_AUTH_LEVEL']) && $_SESSION['SESS_AUTH_LEVEL'] == 3 );
return $result;
}
if (CheckAccess()) {
header("location: admin.php");
} else {
header('WWW-Authenticate: Basic realm=“Test restricted area”');
header('HTTP/1.0 401 Unauthorized');
}
The problem is that there is already output before the headers are send: this need to be changed 问题是在发送标头之前已经有输出:这需要更改
<?php
require_once('check.php');
?>
<?php
//This function returns True if auth level = '3'
//Otherwise it returns False
function CheckAccess()
{
...
to this 对此
<?php
require_once('check.php');
//This function returns True if auth level = '3'
//Otherwise it returns False
function CheckAccess()
{
...
because the headers needs to be sent first then the content :) 因为标题需要先发送然后内容:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.