6

I am using mkdir to create normally 2 nested directories for a file structure. The directories it creates are always set to 0755. The code I am using however is.

 mkdir('path_one/path_two', 0777, true);

I have tried then doing

 chmod('path_one/path_two', 0777);

but that only sets the final directory as 0777. What would cause mkdir not to function properly?

Case
  • 4,244
  • 5
  • 35
  • 53
  • 1
    To be honest, I think that's how I would expect it to work. Giving the perms to all dirs along the way seems a bit reckless. – goat Sep 07 '13 at 21:25
  • Why would that be reckless? I did just discover a work around, but it doesn't make much sense to me. $old = umask(0); mkdir($dir, 0777, true); umask($old); – Case Sep 07 '13 at 21:27
  • In the first event I expect that your `umask` is set to `755`. – Waleed Khan Sep 07 '13 at 21:30
  • It's reckless because it would not be expected behavior. The GNU (unix) mkdir() command also does not recursively set permissions with the --mode option. – micah94 Sep 07 '13 at 21:52

2 Answers2

6

mkdir is functioning correctly. The intermediate directories created are set based on the current umask. You want something like:

umask(0777);
mkdir('path_one/path_two', 0777, true);
Tim Duncklee
  • 1,420
  • 1
  • 23
  • 35
  • 4
    This will not work. If the `umask` is `0777` every directory will be created with mode `0-0-0`. To achieve `0777` you have to set the umask to `0`. – DerVO Nov 15 '18 at 10:28
3

From the php manual:

The mode is also modified by the current umask, which you can change using umask().

Note that any bits that are set in umask() are unset in the result that's used by mkdir(). The default umask is 0022 and the default create mode for mkdir is 0777, which gives a result value of 0755. This applies for all created directories.

Arjan
  • 9,784
  • 1
  • 31
  • 41