Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

posix_getgrnam() returns a limited number of members from "members" array

Tags:

php

posix

I am trying to read all members of a group by using one of PHP's POSIX functions posix_getgrnam(). According to PHP manual, it should return an array of strings for ALL the members in the group:

members This consists of an array of string's for all the members in the group.

I need to check if the user is in the specific group.

However, I faced an interesting issue - I only get 65 members - indexes from [0] to [64], and the group actually has more than 700 members.

Here is my code:

function checkUserInGroup($user_name)
{
    $group_info = posix_getgrnam("test");   
    for ($i=0; $i < count($group_info["members"]); $i++) { 
        $user = $group_info["members"][$i];             // "members" is an array inside $group_info array

        print_r($group_info["members"]);                  // THIS IS WHERE I GET ONLY 65 MEMBERS

        if ($user == "$user_name") {                       // If username is found, then he/she is in the group
            return true;
            break;
        }
    }
}

Does anyone know why this is the case?

like image 406
tera_789 Avatar asked Sep 18 '25 16:09

tera_789


1 Answers

posix_getgrnam() only returns the list of users that have the group as a secondary group. To check the user's primary group, call posix_getpwnam() and check the user's GID.

function checkUserInGroup($user_name, $group_name)
{
    $group_info = posix_getgrnam($group_name);   
    $user_info = posix_getpwnam($user_name);
    return $user_info['gid'] == $group_info['gid'] || in_array($user_name, $group_info["members"]);
}
like image 147
Barmar Avatar answered Sep 20 '25 07:09

Barmar