即使文件夹有777的权限问题

Permission problem even the folder has 777

我对这段代码有疑问:

final public function logToSystem(string $message = '', string $anyName = '')

{
    if(!file_exists(PATH_ROOT . '/logs')) {
        mkdir(PATH_ROOT . '/logs', 777);
    }

    if(!is_writable(PATH_ROOT . '/logs/api_submissions_' . escapeshellarg($anyName) . '.log')) {
        throw new Exception('ABORTING! Can not write to file: ' . PATH_ROOT . '/logs/api_submissions_' . escapeshellarg($anyName) . '.log');
    }

    file_put_contents(PATH_ROOT . '/logs/api_submissions_apiAction.log', $message, FILE_APPEND);
}

/logs/ 存在并且有 777 个。我已经将所有权设置为 www-data。

如果我想向我的 API 发送任何数据,我会收到此错误:

[php7:error] [pid 544753] [client 12345:43019] PHP Fatal error: Uncaught Exception: ABORTING! Can not write to file: /var/www/html/logs/api_submissions_''.log in /var/www/html/admin/lib/controller/Controller_Admin_Articles.class.php:377\nStack trace:\n#0 /var/www/html/admin/lib/controller/Controller_Admin_Articles.class.php(492): Controller_Admin_Articles->logToSystem()\n#1 /var/www/html/core/lib/controller/Dispatcher.class.php(20): Controller_Admin_Articles->submitApiArticle()\n#2 /var/www/html/admin/index.php(7): Dispatcher::dispatch()\n#3 {main}\n thrown in /var/www/html/admin/lib/controller/Controller_Admin_Articles.class.php on line 377

有什么想法吗?

如果函数$anyName的参数是空字符串,则应在创建文件之前更改

if ($anyName === '') {
    $anyName = time();
}

或者做一些其他的逻辑来创建一个唯一的名字

还要注意file_put_contents(PATH_ROOT . '/logs/api_submissions_apiAction.log', $message, FILE_APPEND); 这里你没有使用这段代码上面写权限检查过的文件名

此外,在带有 is_writable 函数的 if 语句之前,如果文件不存在,您应该创建该文件,或者将 file_exists 添加到 if 语句中以进行额外检查(以确保)文件是否确实存在.否则 is_writable 函数将始终 return false 因为该文件不存在于您的文件系统中。 Please check

我建议使用这样的代码

if(!file_exists(PATH_ROOT . '/logs')) {
    mkdir(PATH_ROOT . '/logs', 777);
}
if ($anyName === '') {
    $anyName = time(); // or any other file name, depends on your needs
}

$fileName = PATH_ROOT . '/logs/api_submissions_' . escapeshellarg($anyName) . '.log';
if(file_exists($fileName) && !is_writable($fileName)) {
    throw new Exception('ABORTING! Can not write to file: ' . $fileName);
}

file_put_contents($fileName, FILE_APPEND);