2

I can set file permissions using chmod:

$file = 'somefile.txt';
$mode = 0755;

chmod($file, $mode);

How do I check if the mode is valid? It seems entering a random mode will really mess up the file permissions.

Like:

if (mode_is_valid($mode)) {
  chmod($file, $mode);
}

2 Answers 2

2

Just check, if the mod is in the given number range. I.e.

function mode_is_valid($mode) {
    if (is_string($mode)) {
        $mode = octdec($mode);
    }
    return $mode >= 0 && $mode <= 0777;
}

If you want also to take care about special permissions, you need to add additional logic.

3
  • I don't think 99 or 301 are valid modes. Might want to improve this answer.
    – CollinD
    Commented Jun 22, 2018 at 19:06
  • @CollinD you speaking about the string 99 or the number? The number has a octal representation, which is of course valid: 99 = 0143 - perfectly valid mode..
    – Philipp
    Commented Jun 22, 2018 at 19:09
  • Completely disregarded the octal notation. My bad. I'd remove my vote if I could
    – CollinD
    Commented Jun 22, 2018 at 19:11
0

chmod follows the classic Unix / Linux file mode logic. The number represents a bit pattern in OCTAL !! notation. There are 9 bits for read / write / execute plus some additional flags for special treatment like inheritance of ownership (the so called S-Bit) ...

Order of the 9 bits is:

3 bits for "owner" of the file / link / directory
3 bits for "group" of the file / link / directory
3 bits for the rest of the world

Individual bits represent

READ permission
WRITE permission
EXECUTE permission

Example

READ (1) WRITE (1) EXEC (1) = binary 111 = octal 7
READ (1) WRITE (1) EXEC (0) = binary 110 = octal 6
READ (1) WRITE (0) EXEC (0) = binary 100 = octal 4

The three combinations above are the most common ones. READ + EXEC = 5 is also common. The EXEC is needed on directories to allow directory listing.

On Windows this is emulated as the underlying file system permits.

So avoid anything that removes the owners permission to read the file. If the web-server UID is not the owner but the group and the web-server process should be able to read the file, also avoid removal of the read permission in the second digit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.