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

Firefog
  • 3,094
  • 7
  • 48
  • 86
  • Does this answer your question? [How to use PHP in\_array with associative array?](https://stackoverflow.com/questions/21809116/how-to-use-php-in-array-with-associative-array) – catcon Aug 09 '20 at 22:15
  • Your problem is that the value is wrapped inside another array within the one you're checking. in_array won't check inside any objects or arrays it finds, it only looks at the first level down. This might answer your question: [Check if a specific value exists at a specific key in any subarray of a multidimensional array](https://stackoverflow.com/questions/6990855/check-if-a-specific-value-exists-at-a-specific-key-in-any-subarray-of-a-multidim) – ADyson Aug 09 '20 at 22:15

1 Answers1

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.

Bartosz Pachołek
  • 1,278
  • 1
  • 8
  • 17