>我已经将数组保留在会话中,如果用户角色是管理员和其他角色,我想将用户重定向到管理员。但我做不到??我不知道问题出在哪里。会话运行不正常。谁能帮我??
$session_user = array($user_id = $row['user_id'],
$fullname = $row['fullname'],
$username = $row['username'],
$phone_number = $row['phone_number'],
$state = $row['state'],
$city = $row['city'],
$street = $row['street'],
$email = $row['email'],
$user_role = $row['user_role']);
$_SESSION['userdata'] = $session_user;
/*header('Location:hello.php');*/
if($_SESSION['userdata']== 'admin'){
/*header('Location:admin/admindashboard.php');*/
header('Location:hello.php');
}else{
/*header('Location:contributor/contributordashboard.php');*/
/*header('Location:hello.php');*/
echo "Error in identifying the user role";
}
您的数组中似乎存在键入错误。不能使用 php 变量和等运算符赋值。您需要使用箭头运算符。假设以下数组
$session_user = array('user_id' => $row['user_id'],
'fullname' => $row['fullname'],
'username' => $row['username'],
'phone_number' => $row['phone_number'],
'state' => $row['state'],
'city' => $row['city'],
'street' => $row['street'],
'email' => $row['email'],
'user_role' => $row['user_role']);
改变
$_SESSION['userdata']
自
$_SESSION['userdata']['user_role']
获取user_role,因为您要在会话中存储数组。如下所示:
if($_SESSION['userdata']['user_role']== 'admin'){
/*header('Location:admin/admindashboard.php');*/
header('Location:hello.php');
}else{
/*header('Location:contributor/contributordashboard.php');*/
/*header('Location:hello.php');*/
echo "Error in identifying the user role";
}
附言:您可以使用以下方法检查您的user_role索引
echo "<pre>"
print_r($_SESSION['userdata']);
echo "</pre>"
希望这会有所帮助。
尝试在 IF 子句之前(暂时(添加以下行:
print_r($_SESSION);
这将输出会话数组,以便您可以确定其中user_role变量的确切位置。
看起来 $_SESSION['userdata'] 包含一个数组。
最好的办法是用户角色将包含在
$_SESSION['userdata']['user_role']
但print_r应该给你明确的答案,而不是反复试验
$_SESSION['userdata']
的值是一个TRUE
的数组(PHP 中的赋值导致值 TRUE。在PHP数组中是名称到值对,名称应该是一个字符串,后跟=>
,然后是值。例如:
$session_user = array('user_id' => $row['user_id'],
...
然后,您可以使用@Sehdev建议的值。
当您不确定变量/数组是否已正确填充所需的值时,您可以执行var_dump($session_user);
$session_user = [
'user_id' => $row['user_id'],
'fullname' => $row['fullname'],
'username' => $row['username'],
'phone_number' => $row['phone_number'],
'state' => $row['state'],
'city' => $row['city'],
'street' => $row['street'],
'email' => $row['email'],
'user_role' => $row['user_role']
];
这应该为您提供正确的索引。
$session_user->user_role
赋予你角色
$_SESSION['usersata']['user_role']
也应该返回您的角色。