php – Permissions with mkdir won't work-ThrowExceptions

Exception or error:

I can’t understand why I have to use chmod to get the correct permissions..
The file is created succesfully but with 0755 and not 0775 that I specify in mkdir .

( )

I have to do chmod after mkdir to set the correct permissions.

Safe mode is off in php.ini and the folder belongs to php’s group and owner (www-data)

This doesn’t work:



But this does:


How to solve:

Yes, it’s because of umask…

from comments of docs:

You might notice that when you create
a new directory using this code:

mkdir($dir, 0777);

The created folder actually has
permissions of 0755, instead of the
0777. Why is this you ask? Because of umask():

The default value of umask, at least
on my setup, is 18. Which is 22 octal,
0022. This means that when you use mkdir() to CHMOD the created folder to
0777, PHP takes 0777 and substracts
the current value of umask, in our
case 0022, so the result is 0755 –
which is not what you wanted,

The “fix” for this is simple, include
this line:

$old_umask = umask(0);

Right before creating a folder with
mkdir() to have the actual value you
put be used as the CHMOD. If you would
like to return umask to its original
value when you’re done, use this:



I think you may have to modify your umask.

As noted on the mkdir manpage:

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

Now, looking at the umask() manpage, one of the comment listed confirms my inner thought:

“It is better to change the file permissions with chmod() after creating the file.”

In other words, I believe the way you are doing it is more secure:

Set your umask so that files are created private to your user, then use chmod to open them up.


Try calling this function before you make your directory: clearstatcache(); Also, maybe you should check if you can do it using just mkdir if you siwtch to another user.

Leave a Reply

Your email address will not be published. Required fields are marked *