MultiDev
MultiDev

Reputation: 10659

PHP: How to check if a valid CHMOD mode?

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);
}

Upvotes: 2

Views: 879

Answers (2)

Philipp
Philipp

Reputation: 15639

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.

Upvotes: 2

maba
maba

Reputation: 1

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.

Upvotes: 0

Related Questions