tags:

views:

125

answers:

3

I've been studying WordPress source code that operates on the filesystem, when I hit these few lines and I'm really not quite sure what they do?

$stat = stat( dirname( $new_file ));
$perms = $stat['mode'] & 0000666;
@ chmod( $new_file, $perms );
+1  A: 

It changes the permission to allow writing in a directory.. I think. Check out stat() and chmod().

metrobalderas
Pekka
It drops the extra bits and retains only the `rwxrwxrwx` part, whichever bits of it are set.
Blindy
A: 

0666 is the octal notation for the unix rwxrwxrwx permissions, so I'm assuming the $stat['mode'] returns the permissions of the folder. Then they get bitwise AND'ed with the 0666 mask to check if you have at least read/write/execute permissions for self, group and others.

Blindy
`x` permissions are bit 0 (1 in hex/octal), these are not set. So 666 means rw-rw-rw-. Also, the AND operator only keeps bits that are 1 in *both* operands, so the code actually *removes* all permissions that are *not* read/write.
Wim
+3  A: 

That code uses bitwise operations to ensure that a file's permissions are no higher than 666. To break it down:

// Retrieves the file details, including current file permissions.
$stat = stat( dirname( $new_file )); 

// The file permissions are and-ed with the octal value 0000666 to make
// sure that the file mode is no higher than 666. In other words, it locks
// the file down, making sure that current permissions are no higher than 666,
// or owner, group and world read/write.
$perms = $stat['mode'] & 0000666; 

// Finally, the new permissions are set back on the file
@chmod( $new_file, $perms );
Jon Benedicto
"to ensure that a particular file attribute is set" -- or "not set" in this case: everything that is not contained in 666 (rw-rw-rw-) is removed -- in practice this means execute bits.
Wim
Much appreciated Jon! But I'm guessing if the file perms were already, for example, 600, then $perms would remain 600?
TheDeadMedic
@TheDeadMedic - Correct. The code only removes permissions, it does not add them.
Jon Benedicto