0

In PHP (and Linux), I am able to get the list of users that belong to a given group by using posix_getgrnam(), but I would like to go on the opposite way. That means, I would like to get the list of groups to which a given user belongs. How can I do it?

  • 1
    Use `posix_getgroups` – kainaw Aug 18 '15 at 19:40
  • @kainaw That gets the groups of the current process, it doesn't take a username. – Barmar Aug 18 '15 at 19:41
  • I don't think POSIX has a function like this, so there's nothing for PHP to call to do it. – Barmar Aug 18 '15 at 19:41
  • Yes. Posix is limited to the running process. The system itself allows it, but then you have system dependent code. For example, you can grab the output of `grep username /etc/group | cut -d: -f3` to get a list of group IDs from a standard linux/unix system. – kainaw Aug 18 '15 at 19:43
  • @kainaw you don't need to manipulate /etc/group, a linux system should have a groups command. http://stackoverflow.com/questions/350141/how-to-find-out-what-group-a-given-user-has – Devon Bessemer Aug 18 '15 at 19:50
  • @Devon Correct. Linux has a groups command. For this need, I prefer to hit the file. The output of groups is formatted as `username : group1 group2 group3`. The output of the grep/cut command I used is just each group on a separate line. Combined with exec, you can easily end up with an array of group names. – kainaw Aug 18 '15 at 23:11

2 Answers2

0

shell_exec() + How to find out what group a given user has?

No built in functions for getting groups of a user.

Community
  • 1
  • 1
Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95
  • That's how I do today... But I was wondering if I could use any PHP native function instead. Isn't the shell_exec approach much slower? – Rafael Guimaraes Aug 18 '15 at 19:58
  • Slower than native functions, sure, but noticeable? Probably not unless you are running this command thousands of times. – Devon Bessemer Aug 18 '15 at 19:59
0

use stats function https://www.php.net/manual/en/function.stat.php

$stat = stat($filename);
echo $stat['gid'];