我根据角色重定向用户;
username | password | accessLevel
xxxxxx xxxxxx admin
xxxxxx xxxxxx member
xxxxxx xxxxxx none
我有以下 check.php 页面;
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Define $myusername and $mypassword
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "index.php"
$_SESSION['myusername']= $myusername;
$_SESSION['mypassword']= $mypassword;
$role = mysql_fetch_array($result);
if($role['accessLevel'] == "admin"){
header("location:index.php");
exit();
}
elseif($role['accessLevel'] == "member"){
header("location:tasks.php");
exit();
}
else {
echo "Error: Username, Password or Access Level incorrect! Go Home, you're Drunk!!!";
}
}
ob_end_flush();
?>
这会将正确的角色重定向到正确的页面,但是如果他们在同一目录中键入页面,他们也可以访问我不希望他们访问的其他页面,我想将“成员”限制为某些页面和“管理员”对于所有页面,我需要在页面顶部添加什么来区分 2 个用户角色?
我的所有页面顶部都有以下内容;
<?php
session_start();
////if(!session_is_registered(myusername)){
if (!isset($_SESSION['myusername'])) {
header("location:main_login.php");
}
我可以更改此设置以限制依赖于访问级别的页面吗?
最佳答案
非常简单,我几乎在所有项目中都这样做了, 你要做的是, 替代方案1。 将角色作为用户名传递到 session 中,成功登录后,然后在每个页面的顶部启动 session 并检查权限。 例如:admin的index.php
<?php
session_start();
if($_SESSION['accessLevel'] !== "admin"){ header("location:Adminlogin.php"); }
?>
<!-- go whith your page -->
与成员(member)的tasks.php相同
<?php session_start();
if($role['accessLevel'] !== "member"){header("location:Memberlogin.php"); } ?>
替代方案2。 为成员和管理员提供不同的 session ID,
示例:来自您的代码部分...
<?php
//fetch its role in DB then assign, like
if($role['accessLevel'] == "admin"){
$_SESSION['admin']=$role['username'];
header("location:index.php");
}
elseif($role['accessLevel'] == "member"){
$_SESSION['member']=$role['username'];
header("location:tasks.php");
}
然后在加载整页之前首先检查访问权限,就像我上面所做的那样 如果对于
$_SESSION['admin']
或
$_SESSION['member'].
关于php - 根据角色重定向到页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26568154/