我有一个将文件存储到目录中的脚本。该功能基于当前日期(2018年> 3月>周1,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 ....它很有效
答案 0 :(得分:1)
mkdir($filepath[$mode] . $year);
这不符合你的想法。它从$mode
获取索引$filepath
处的字符,向其附加$year
,并在结果处创建目录(不显式设置权限)。由于$filepath
中没有512个字符(0777
在八进制中为511),$filepath[$mode]
返回一个空字符串(带有“未初始化的字符串偏移”通知)和{{1}尝试在mkdir
创建目录。
$year
有多个参数,第二个是模式:
mkdir
但是mkdir
's default mode is 0777
,所以如果目录权限最终不同,your umask
is getting in the way。您可以set your umask
to allow 0777
permissions,但在创建目录后,chmod
目录更容易且(可能)更安全:
mkdir($filepath . $year, $mode);
答案 1 :(得分:0)
存储文件夹应该由apache写入。
您可以将权限设置为777或将文件夹所有权转移到apache。即,chown到apache用户
在ubuntu chown -R www-data:www-data storage /
答案 2 :(得分:0)
你应该使用shell_exec
php函数:
shell_exec('chmod -R 777 storage/');
shell_exec('chown -R www-data:www-data storage/');