有没有办法在PHP中的mkdir()或chmod()中设置字符串权限模式


Is there a way to set a string permission mode in mkdir() or chmod() in PHP?

当我查找mkdir()和chmod()的PHP手册时,发现这两个函数都需要一个整数值(例如mkdir( 'a/dir/path', 0700, false);)。我确实看到我可以在mode参数上使用其他模式,比如inval()或ocdec(),所以我想知道<字符串有这样的东西吗>

例如,mkdir( 'a/dir/path', strval( 'u+rwx' ), false );。这样做的原因是,当其他对PHP没有经验的人阅读我的代码时,我设置的权限会更明显。

首先,我不认为实现这种功能是严格必要的:数字权限对于那些知道如何读取它们的人来说实际上是直观的。

然而,为了回答这个问题,要转换类似"-rwxrw-"的字符串,可以使用以下函数:

注意:您应该在下面的函数中添加一些输入验证(检查字符串长度、有效字符等)

function format($permissions)
{
    //Initialize the string that will contain the parsed perms.
    $parsedPermissions = "";
    //Each char represents a numeric constant that is being added to the total
    $permissionsDef = array(
        "r" => 4,
        "w" => 2,
        "x" => 1,
        "-" => 0
    );
    //We cut the first of the 10 letters string
    $permissions = substr($permissions, 1);
    //We iterate each char
    $permissions = str_split($permissions);
    $length = count($permissions);
    $group = 0;
    for ($i = 0, $j = 0; $i < $length; $i++, $j++) {
        if ($j > 2) {
            $parsedPermissions .= $group;
            $j = 0;
            $group = 0;
        }
        $group += $permissionsDef[$permissions[$i]];
    }
    $parsedPermissions .= $group;
    return $parsedPermissions;
}

AFAIK没有内置的方法。我也认为没有必要这样做http://www.onlamp.com/pub/a/php/2003/02/06/php_foundations.html应该足够了:

Value   Permission Level
--------------------------
400     Owner Read
200     Owner Write
100     Owner Execute
 40     Group Read
 20     Group Write
 10     Group Execute
  4     Global Read
  2     Global Write
  1     Global Execute
Permission Calculations:
------------------------
   400  Owner Read
+  100  Owner Execute
+   20  Group Write
+    4  Global Read
-----------------------------
= 0524  Total Permission Value

这比编写一个函数来正确地解析所有可能用作文件权限的字符串更容易。