0

我有一个将文件存储到目录中的脚本。该函数基于当前日期(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.... 中删除那段代码,它会很好用。

4

3 回答 3

1
mkdir($filepath[$mode] . $year);

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

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

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

但是mkdir它的默认模式是0777,所以如果目录权限最终不同,umask就会碍事。您可以将您的权限设置umask为允许0777chmod但在创建目录后它更容易并且(可能)更安全:

mkdir($filepath . $year);
chmod($filepath . $year, $mode);
于 2018-03-12T02:08:20.430 回答
0

storage 文件夹应该是 apache 可写的。

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

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

于 2018-03-10T06:27:16.493 回答
0

你应该使用shell_execphp函数:

shell_exec('chmod -R 777 storage/');
shell_exec('chown -R www-data:www-data storage/');
于 2018-03-10T09:50:30.553 回答