Home » Php » php – Recursive mkdir() and chmod()?

php – Recursive mkdir() and chmod()?

Posted by: admin July 12, 2020 Leave a comment

Questions:

When using mkdir() with the recursive flag set to true do all the created directories get the specified chmod or just the last one? For example:

mkdir('/doesnotExist1/doesnotExist2/doesnotExist3/', 0755, true);

Will the newly created directories /doesnotExist1/ and /doesnotExist1/doesnotExist2/ also get the same chmod as /doesnotExist1/doesnotExist2/doesnotExist3/ = 0755?

If not, is there any way to force the above behavior?

I would test this myself, but I don’t have access to a *nix box ATM.

How to&Answers:

Just tested on gentoo linux with PHP 5.2.12: They all have the same permissions.

[email protected]:~$ php -a
Interactive shell

php > mkdir('asd/def/ghi', 0700, 1);
php > ^C
[email protected]:~$ ls -hal asd
total 12K
drwx------  3 soulmerge soulmerge 4.0K 2010-01-12 10:32 .
drwxr-xr-x 79 soulmerge soulmerge 4.0K 2010-01-12 10:32 ..
drwx------  3 soulmerge soulmerge 4.0K 2010-01-12 10:32 def

Answer:

The C function responsible for mkdir(‘localfilesystem’, x, true) is php_plain_files_mkdir() in main/streams/plain_wrapper.c. And it calls php_mkdir(dir, mode TSRMLS_CC); for the “first” directory it is supposed to create and VCWD_MKDIR(buf, (mode_t)mode)) for all subdirectories. php_mkdir() does some safe mode checking and then also calls VCWD_MKDIR
So yes, the mode parameter is used for all directories created by mkdir(p, x, true).