简体   繁体   中英

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

When I looked up the PHP Manual for mkdir() and chmod(), it appears that both functions expect an integer value (eg mkdir( 'a/dir/path', 0700, false ); ). I did see that there are other modes I can use such as inval() or ocdec() on the mode parameter, so I'm wondering... is there something like that for strings?

For example, mkdir( 'a/dir/path', strval( 'u+rwx' ), false ); . The reason for this is so that when other people who are (also) not as experienced in PHP read my code, it will be more apparent what permissions I'm setting.

First of all, I don't think that it is strictly necessary to implement that kind of function: numeric permissions are actually intuitive for those who know how to read them.

However, to answer the question, to convert a string like " -rwxr-xrw- " you could use something like this function:

NB: you should REALLY add some input validation to the function below (check string length, valid chars, etc..)

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 there is no inbuilt way of doing it. I also do not think there is a need for it. A link to an explanation of file permissions and a comment such as this one fromhttp://www.onlamp.com/pub/a/php/2003/02/06/php_foundations.html should suffice:

 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

This is easier than writing a function to correctly parse all the possible strings that can be used as file permissions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM