Join or Login

convert chmod php function

by mr. H8ers


Sometimes you just want a function to convert chmod from 3-digit numeric to string and vice-versa.
The input must be a 3 digit string or a 9 characters long string. This function does not check for leading 0 on 4 digit permission scheme or the ‘-’ (file) or ‘d’ (directory) on 10 character long string permission scheme.
Here is a simple function to do this it is as simple as I would like to make it and works well for me enjoy.


function convert_chmod($chmod)
{
    if(isset($chmod) && is_string($chmod))
    {
        $testArray = array('---', '--x', '-w-', '-wx', 'r--','r-x','rw-','rwx');
        $length = strlen($chmod);
        $perm = null;
        
        if(is_numeric($chmod) && $length == 3) {
            $testArray = array_flip($testArray);
        }elseif($length == 9 && trim($chmod, '-rxw') == '' ) {
            $chmod = str_split($chmod, 3);
        }else {
            trigger_error('convert_chmod paramater 1 expects string with a ' .
                'length of 3 or 9. example: "644" "r--r-xr-x"', E_USER_WARNING);
            return;
        }

        for($i = 0; $i < 3;$i++) {
            if(in_array($chmod[$i], $testArray)) {
                $perm .= array_search($chmod[$i], $testArray );
            }
        }
        return $perm;
    } else{
        return;
    }
}

Leave a Reply

Powered by WordPress