mkdir() 创建 0755 而不是 0775

mkdir() creating 0755 instead of 0775

我有以下代码:

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

$dir = 'path/to/folder/';

makedirs($dir, 0775);

问题是: 即使将 0775 或任何其他内容作为参数传递给 $modemkdir() 也会创建 0755 许可文件夹。

例如 previows 代码将 return:

您可以执行以下操作

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);

注意 : 虽然你可以使用 umask(0) 允许甚至 777 权限但不推荐,因为它可能会带来安全问题。

编辑

尝试为所有用户或您自己设置系统范围的 umask 值,以从 php 中删除 umask 代码。 虽然上面的代码可以工作,但不建议在 php 脚本中设置 umask。

根据 PHP 手册页

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.

您可以在 /etc/bashrc 或 /etc/profile 文件中为所有用户设置 umask。 默认情况下,大多数 Linux 发行版将其设置为 0022 (022) 或 0002 (002)。打开/etc/profile或~/.bashrc文件,输入:

# vi /etc/profile

$ vi ~/.bashrc

Append/modify 以下行设置新的 umask: umask 022

保存并关闭文件。更改将在下次登录后生效。所有 UNIX 用户都可以在他们的 /etc/profile 文件、~/.profile (Korn / Bourne shell) ~/.cshrc 文件 (C shells)、~/. bash_profile (Bash shell) 或 ~/.login 文件(定义用户登录时的环境)。

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