0

I am making a PHP user permission system where all permission related to specific role are saved in session as like array but when I try to check the it does not true where already the value exists in array.

Here is my session array $_SESSION['userPermissions'] = $userPermissions; here is the var_dump of $_SESSION['userPermissions']

output

You are now logged inarray(6) { [0]=> array(1) { ["permission_name"]=> string(11) "create-role" } [1]=> array(1) { ["permission_name"]=> string(11) "update-role" } [2]=> array(1) { ["permission_name"]=> string(11) "delete-role" } [3]=> array(1) { ["permission_name"]=> string(11) "create-user" } [4]=> array(1) { ["permission_name"]=> string(11) "update-user" } [5]=> array(1) { ["permission_name"]=> string(11) "delete-user" } }

I use bellow function to check array value

 // checks if user can delete an user
  function canDeleteUser() {
    if(in_array('delete-user', $_SESSION['userPermissions'])){
      return true;
    } else {
      return false;
    }
  }

it always return false please help me

2

1 Answer 1

1

In order for your code to work you would need to have your userPermissions array to look as follows:

[ 
   'create-role',
   'delete-user',
   ...the rest...
]

while in fact your array look as follows:

[ 
   ['permission_name' => 'create-role'],
   ['permission_name' => 'delete-user'],
   ...the rest...
]

in order to search for a nested value extract first the column:

if(in_array('delete-user', array_column($_SESSION['userPermissions`], 'permission_name'))){

or search by array:

if(in_array(["permission_name"=>"delete-user"], $_SESSION['userPermissions`]))

yet be aware that the second approach is much less secure: as if the array will change (will have other elements) this will fail. I strongly advise to use the first approach.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.