Why can't PHP create a directory with 777 permissions?

PhpMkdir

Php Problem Overview


I'm trying to create a directory on my server using PHP with the command:

mkdir("test", 0777);

But it doesn't give full permissions, only these:

rwxr-xr-x

Php Solutions


Solution 1 - Php

The mode is modified by your current umask, which is 022 in this case.

The way the umask works is a subtractive one. You take the initial permission given to mkdir and subtract the umask to get the actual permission:

  0777
- 0022
======
  0755 = rwxr-xr-x.

If you don't want this to happen, you need to set your umask temporarily to zero so it has no effect. You can do this with the following snippet:

$oldmask = umask(0);
mkdir("test", 0777);
umask($oldmask);

The first line changes the umask to zero while storing the previous one into $oldmask. The second line makes the directory using the desired permissions and (now irrelevant) umask. The third line restores the umask to what it was originally.

See the PHP doco for umask and mkdir for more details.

Solution 2 - Php

The creation of files and directories is affected by the setting of umask. You can create files with a particular set of permissions by manipulating umask as follows :-

$old = umask(0);
mkdir("test", 0777);
umask($old);

Solution 3 - Php

Avoid using this function in multithreaded webservers. It is better to change the file permissions with chmod() after creating the file.

Example:

$dir = "test";
$permit = 0777;

mkdir($dir);
chmod($dir, $permit);

Solution 4 - Php

For those who tried

mkdir('path', 777);

and it did not work.

It is because, apparently, the 0 preceding the file mode is very important which tells chmod to interpret the passed number as an Octal instead of a decimal.

Reference

Ps. This is not a solution to the question but only an add-on to the accepted anwser

Solution 5 - Php

Probably, your umask is set to exclude those

Solution 6 - Php

In my case, I have to use the following way for centos7, which solved the problem

$oldmask = umask(000);//it will set the new umask and returns the old one 
mkdir("test", 0777);
umask($oldmask);//reset the old umask

More details can be found at https://www.php.net/manual/en/function.umask.php

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSjwdaviesView Question on Stackoverflow
Solution 1 - PhppaxdiabloView Answer on Stackoverflow
Solution 2 - PhpSteve WeetView Answer on Stackoverflow
Solution 3 - PhpStanislav MalomuzhView Answer on Stackoverflow
Solution 4 - PhpNiket PathakView Answer on Stackoverflow
Solution 5 - PhpThe Archetypal PaulView Answer on Stackoverflow
Solution 6 - PhpMahesh HegdeView Answer on Stackoverflow