阻止用户访问管理区域


Prevent users from accessing admin area

美好的一天,

我的管理员控制面板PHP页面面临代码错误。

我想阻止任何其他用户访问此页面,除非他的 job_title= 管理员。

它可以工作,但即使是管理员 himslef 也会再次重定向回登录页面!

这是代码

<?php
include('db.php');
?>
<?php
// Inialize session
@session_start();
ob_start();
// Check, if username session is NOT set then this page will jump to login page
if (!isset($_SESSION['name']) || ($_SESSION['job_title'] != "admin")) {
header('Location: index.php');
}
ob_flush();
?>
>?
<!-- STARTING HTML FORMAT !-->

?>

有什么帮助吗?

试试这个,如果仍有问题,请告诉我。

$_SESSION['name'] = 'dennis';
$_SESSION['job_title'] = 'admin';
if (!isset($_SESSION['name']) || (!isset($_SESSION['job_title']) ? false: ($_SESSION['job_title'] !== 'admin'))) {
    echo 'Redirecting';
} else {
    echo 'You''re good! Not redirecting!';
}

这可能是一种更容易理解的方法,只需放入一个函数中即可。

$_SESSION['name'] = 'dennis';
$_SESSION['job_title'] = 'admin';
if (!isset($_SESSION['name']) || !isBoss()) {
    echo 'Redirecting';
} else {
    echo 'You''re good! Not redirecting!';
}
function isBoss() {
    if (isset($_SESSION['job_title']))
        if ($_SESSION['job_title'] === 'admin')
            return true;
    return false;
}

我认为您的问题是fubar换行符:)添加了登录页面引用,该引用将取消设置登录失败时检查的会话变量。

非常小心放置<?php ?>标签的位置 - 在 .inc 文件中,例如 db.php include - 您可以在最后一行省略结束?>标签以避免意外 ENTER 和 CTRL + S 失败,在输出缓冲区 (ob) 中潜入不需要的换行符字符。如果激活了ob_start,则在选择或脚本结束之前,不会从服务器写入任何内容。否则,如果不是,则默认为每个 ' 将刷新输出并启动有效负载的内容部分。

登录.php:

<?php
session_start(); // put this on top-most line in your script
$ok = check($_POST['user'], $_POST['pass']);
if($ok) {
 $user = db_get_user_creds($_POST['user']);
 $_SESSION['name'] = $user['name'];
 $_SESSION['job_title'] = $user['job_title'];
} else {
 // session_unset();
 unset($_SESSION['name']);
 unset($_SESSION['job_title']);
}
?>

管理员.php

<?php
session_start(); // put this on top-most line in your script
// or, use ob_start at the very first line
// (with no widespace what so ever written out before it)
include('db.php');
?> I am writing out a newline here, session / header section is going to become unstable
<?php
// Inialize session
// @session_start(); moved up top
ob_start();
// Check, if username session is NOT set then this page will jump to login page
if (!isset($_SESSION['name']) || ($_SESSION['job_title'] != "admin")) {
header('Location: index.php');
}
ob_flush();
?>

请参阅"我在这里写出换行符"位

往下走一点;通信流程是这样的:

1) HEADERS such as
Connection: keep-alive'r'n
Content-Type: text/html'r'n    (etc)
2) DOUBLE NEWLINE (one newline with no previous chars on that line)
'r'n
3) CONTENTS
Body
Of Page