【问题标题】:Permission problem even the folder has 777即使文件夹有777的权限问题
【发布时间】:2021-12-16 22:48:54
【问题描述】:

我对这段代码有疑问:

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

有什么想法吗?

【问题讨论】:

  • /var/www/html/logs/api_submissions_''.log您的文件名未正确创建

标签: php permissions


【解决方案1】:

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

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

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

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

同样在带有is_writable 函数的if 语句之前,如果文件不存在,您应该创建文件,或者在if 语句中添加file_exists 以进行额外检查(确定)如果文件确实存在。否则,is_writable 函数将始终返回 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-11
    • 2010-12-24
    • 1970-01-01
    • 2015-03-14
    • 2016-06-07
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    相关资源
    最近更新 更多