【问题标题】:Set File permission when creating directory创建目录时设置文件权限
【发布时间】:2018-08-18 12:20:07
【问题描述】:

我有一个将文件存储到目录中的脚本。该函数基于当前日期(2018>March>week1,2,3 等)每 7 天创建一个新目录。它工作得非常好,但我需要将目录权限设置为 777,否则我会遇到问题。请参阅下面的代码。

static function initStorageFileDirectory() {
    $filepath = 'storage/';

    $year  = date('Y');
    $month = date('F');
    $day   = date('j');
    $week  = '';
    $mode = 0777;

    if (!is_dir($filepath . $year)) {
        //create new folder
        mkdir($filepath[$mode] . $year);
    }

    if (!is_dir($filepath . $year . "/" . $month)) {
        //create new folder
        mkdir($filepath[$mode] . "$year/$month");
    }

    if ($day > 0 && $day <= 7)
        $week = 'week1';
    elseif ($day > 7 && $day <= 14)
        $week = 'week2';
    elseif ($day > 14 && $day <= 21)
        $week = 'week3';
    elseif ($day > 21 && $day <= 28)
        $week = 'week4';
    else
        $week = 'week5';

    if (!is_dir($filepath . $year . "/" . $month . "/" . $week)) {
        //create new folder
        mkdir($filepath[$mode] . "$year/$month/$week");
    }

    $filepath = $filepath . $year . "/" . $month . "/" . $week . "/";

    return $filepath;
}

如您所见,我设置了 $mode。这可能不是最好的方法:插入 [$mode] 后,它无法完全创建目录,但是如果我从 mkdir($filepath.... 中删除那段代码,它会很好用。

【问题讨论】:

    标签: php vtiger directory-permissions


    【解决方案1】:
    mkdir($filepath[$mode] . $year);
    

    这并不像你认为的那样。它从$filepath 获取索引$mode 处的字符,将$year 附加到它,并在结果中创建一个目录(没有明确设置权限)。由于$filepath 中没有 512 个字符(0777 是八进制的 511),$filepath[$mode] 返回一个空字符串(带有“未初始化的字符串偏移”通知)并且mkdir 尝试在 @ 创建一个目录987654333@.

    mkdir 接受多个参数,其中第二个是模式:

    mkdir($filepath . $year, $mode);
    

    但是mkdir's default mode is 0777,所以如果目录权限最终不同,your umask is getting in the way。您可以set your umask to allow 0777 permissions,但在创建目录后chmod 更容易且(可能)更安全:

    mkdir($filepath . $year);
    chmod($filepath . $year, $mode);
    

    【讨论】:

    • 谢谢,会试一试并报告。似乎是对文件进行 chmod 的更安全的选择。
    【解决方案2】:

    存储文件夹应该是 apache 可写的。

    您可以将权限设置为 777 或将文件夹所有权转移给 apache。即,chown 到 apache 用户

    在ubuntu chown -R www-data:www-data storage/

    【讨论】:

      【解决方案3】:

      你应该使用shell_exec php函数:

      shell_exec('chmod -R 777 storage/');
      shell_exec('chown -R www-data:www-data storage/');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-28
        • 1970-01-01
        • 2012-05-24
        • 1970-01-01
        • 2018-04-26
        • 2010-10-09
        • 2014-05-04
        • 2013-07-11
        相关资源
        最近更新 更多