Machado Machado - 7 months ago 82
PHP Question

mkdir() creating 0755 instead of 0775

I have the following code:

function makedirs($dirpath, $mode = 0775, $recursive = true) {
return is_dir($dirpath) || mkdir($dirpath, $mode, $recursive);
}

$dir = 'path/to/folder/'
makedirs($dir, 0775)


The problem is: even when passing 0775 or anything else as parameter for
$mode
,
mkdir()
creates 0755 permition folders.

For exemple the previows code will return:


  • path/ (0755)

  • to/ (0755)

  • folder/ (0755)


Answer

You could do the following

function makedirs($dirpath, $mode = 0775, $recursive = true) {
    $oldMask=umask(002);
    $status = is_dir($dirpath) || mkdir($dirpath, $mode, $recursive);
    umask($oldMask);
    return $status;
}

$dir = 'path/to/folder/'
makedirs($dir, 0775);

Note : Although you could use umask(0) to allow even 777 permissions It's not recommended as it could pose security issues.

Edit

Try setting the umask value system wide for all users or for yourself to remove the umask code from php. Although the above code would work, setting umask in php scripts is not recommended.

According to the PHP Manual Page

Avoid using this function in multithreaded webservers. It is better to change the file permissions with chmod() after creating the file. Using umask() can lead to unexpected behavior of concurrently running scripts and the webserver itself because they all use the same umask.

You can setup umask in /etc/bashrc or /etc/profile file for all users. By default most Linux distro set it to 0022 (022) or 0002 (002). Open /etc/profile or ~/.bashrc file, enter:

# vi /etc/profile

OR

$ vi ~/.bashrc

Append/modify following line to setup a new umask: umask 022

Save and close the file. Changes will take effect after next login. All UNIX users can override the system umask defaults in their /etc/profile file, ~/.profile (Korn / Bourne shell) ~/.cshrc file (C shells), ~/.bash_profile (Bash shell) or ~/.login file (defines the user’s environment at login).

Source http://www.cyberciti.biz/tips/understanding-linux-unix-umask-value-usage.html