Created
October 11, 2010 17:43
-
-
Save RobertAudi/620925 to your computer and use it in GitHub Desktop.
Format unix permissions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Toggle the formatting of unix permissions between: | |
* - 0644 OR 755 | |
* - -rw-r--r-- | |
* | |
* @param string|int $permissions : The permissions string or int that needs to be formatted. | |
* @param string $is_dir : if true, the first char of the long permissions format will be 'd'. ie: drw-r--r-- | |
* @return string: The formatted permissions. | |
* @author Aziz Light | |
*/ | |
function formatPermissions($permissions, $is_dir = false) | |
{ | |
$permissions_lookup = array( | |
'---', // 0 | |
'--x', // 1 | |
'-w-', // 2 | |
'-wx', // 3 | |
'r--', // 4 | |
'r-x', // 5 | |
'rw-', // 6 | |
'rwx', // 7 | |
); | |
$len = strlen($permissions); | |
$new_permissions = ''; | |
if ($len < 5 && $len > 2) | |
{ // format: 0644 OR 755 | |
if ($len == 4) | |
$permissions = substr($permissions, 1); | |
$permissions = str_split($permissions); | |
$new_permissions .= ($is_dir) ? 'd':'-'; | |
foreach ($permissions as $permission) | |
{ | |
$new_permissions .= $permissions_lookup[(int) $permission]; | |
} | |
} | |
elseif ($len == 10) | |
{ // format: -rw-r--r-- | |
$r = 4; | |
$w = 2; | |
$x = 1; | |
$zero = 0; | |
$permissions = substr($permissions, 1); | |
$permissions = str_split($permissions); | |
$group = 0; | |
for ($i = 0, $j = 0, $max = count($permissions); $i < $max; $i++, $j++) | |
{ | |
if ($permissions[$i] == '-') | |
$permissions[$i] = 'zero'; | |
if ($j > 2) | |
{ | |
$new_permissions .= $group; | |
unset($j, $group); | |
$j = 0; | |
$group = 0; | |
} | |
$group += ${$permissions[$i]}; | |
} | |
// add the last permission digit | |
$new_permissions .= $group; | |
} | |
else | |
{ | |
return $permissions; | |
} | |
return $new_permissions; | |
} // End of formatPermissions |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment