只允许某个组显示页面

时间:2012-12-20 04:03:16

标签: php mysql

我想让某个页面只能查看某个数据库组。我的SQL表设置为:

表:DD_users 列:id |小组|用户名|释义|公会|级别|盐

这是我尝试使用的代码:

// First we execute our common code to connection to the database and start the session
require("common.php");

// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
    // If they are not, we redirect them to the login page.
    header("Location: /DD/index.php");

    // Remember that this die statement is absolutely critical.  Without it,
    // people can view your members-only content without logging in.
    die("Redirecting to /DD/index.php");
}

if($_SESSION['user']['group'] == '0')
{
    // Destroy the session to make them log in again.
    unset($_SESSION['user']);

    // If they are not, we redirect them to the login page.
    header("Location: /DD/index.php");

    // Remember that this die statement is absolutely critical.  Without it,
    // people can view your members-only content without logging in.
    die("Redirecting to /DD/index.php");
}

// Everything below this point in the file is secured by the login system

当我尝试这个时,当我只希望第1组和第2组访问该页面时,会让任何用户组(0,1和2)访问该页面。

2 个答案:

答案 0 :(得分:1)

您没有任何代码可以检查它们是否在第1组或第2组中。只需将代码包裹在if周围。

if($_SESSION['group'] == '1' || $_SESSION['group'] == '2')

还要确保使用isset设置$ _SESSION ['group']。如果未设置,则最后if将失败。

答案 1 :(得分:0)

以另一种方式工作:

require('common.php');
$charname = $_SESSION['user']['username'];
$query = "SELECT adminaccess, guild, username, class, level, active, canRegister, canNews, canActive 
      FROM DD_users 
      WHERE username = ?";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute(array($charname));
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code. 
die("Failed to run query: " . $ex->getMessage());
}

// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();

//print_r($rows);
$group = $rows['0']['adminaccess'];
$guild = $rows['0']['guild'];
$username = $rows['0']['username'];
$class = $rows['0']['class'];
$level = $rows['0']['level'];
$accessAdmin = $rows['0']['adminaccess'];
$canRegister = $rows['0']['canRegister'];
$canNews = $rows['0']['canNews'];
$canActive = $rows['0']['canActive'];