简体   繁体   English

为什么 in_array() 总是返回 false(用户权限)?

[英]Why does in_array() always return false (User Permissions)?

I want to make user permissions based of values in an SQL Database.我想根据 SQL 数据库中的值设置用户权限。 I currently store user permissions in a $_SESSION['Userpermissions'] array, however when I go to check these permissions, in_array always returns false.我目前将用户权限存储在$_SESSION['Userpermissions']数组中,但是当我 go 检查这些权限时, in_array总是返回 false。

I've already tried using the isset method and the array_search method.我已经尝试过使用isset方法和array_search方法。

Here is login.php这是登录名。php

function loginById($user_id)
{
    global $conn;
    $sql = "SELECT u.id, u.role_id, u.username, r.name as role FROM users u LEFT JOIN roles r ON u.role_id=r.id WHERE u.id=? LIMIT 1";
    $user = getSingleRecord($sql, 'i', [$user_id]);


    if (!empty($user)) {
        // put logged in user into session array
        $_SESSION['user'] = $user;
        $_SESSION['success_msg'] = "You are now logged in";
        // if user is admin, redirect to dashboard, otherwise to homepage
        if (isAdmin($user_id)) {
            $permissionsSql = "SELECT p.name as permission_name FROM permissions as p
                            JOIN permission_role as pr ON p.id=pr.permission_id
                            WHERE pr.role_id=?";
            $userPermissions = getMultipleRecords($permissionsSql, "i", [$user['role_id']]);
            $_SESSION['userPermissions'] = $userPermissions;
            header('location: ' . BASE_URL . 'admin/dashboard.php');
        } else {
            header('location: ' . BASE_URL . 'index.php');
        }
        exit(0);
    }
}

Here is the function to check the permissions这里是 function 检查权限

 function canDeletePost() {
    if(in_array('delete-post', $_SESSION['userPermissions'])){
      return true;
    } else {
      return false;
    }
   }

Here is the output of print_r :这是print_r的 output :

Array
(
    [0] => Array
        (
            [permission_name] => delete-user
        )

    [1] => Array
        (
            [permission_name] => create-user
        )

)

And here's the code im using to test这是我用来测试的代码

<?php if (canDeleteUser()){
                      echo "CAN DELETE USER";
                    }else{
                      echo "CANT DELETE USER";
                    }?>

The result is always "CANT DELETE USER"结果始终是“无法删除用户”

You are searching against the values in $_SESSION['userPermissions'] , but those are arrays, not strings.您正在搜索$_SESSION['userPermissions']中的值,但这些值是 arrays,而不是字符串。 Instead, use array_column to get the permission values out of the arrays:相反,使用array_column从 arrays 中获取权限值:

in_array('delete-post', array_column($_SESSION['userPermissions'], 'permission_name'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM