首页 > 解决方案 > 即使文件夹有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

任何的想法?

标签: phppermissions

解决方案


如果函数的参数$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函数将始终返回 false,因为文件系统中不存在该文件。请检查

我建议有这样的代码

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

推荐阅读