Get file permissions, owner and group with PHP
Here are a few functions to help you when interacting with files in your php scripts:
Find the owner of a file:
An array of information about the owner is returned.
function foo_get_file_ownership($file){ $stat = stat($file); if($stat){ $group = posix_getgrgid($stat[5]); $user = posix_getpwuid($stat[4]); return compact('user', 'group'); } else return false; }
Get the four digit file permissions number:
A permissions string is returned. Example: 0755
function foo_get_file_perms($file){ return substr(sprintf('%o', fileperms($file)), -4); }
Convert permissions number to Read Write eXecute format:
Directory Example: 0755 converts to drwxr-xr-x
File Example: 0664 coverts to -rw-rw-r–
function foo_convert_perms_to_rwx($perms, $file){ $rwx = array( '---', '--x', '-w-', '-wx', 'r--', 'r-x', 'rw-', 'rwx' ); $type = is_dir($file) ? 'd' : '-'; $owner = $perms[1]; $group = $perms[2]; $public = $perms[3]; return $type.$rwx[$owner].$rwx[$group].$rwx[$public]; }