php - 即使文件夹有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
函数将始终返回 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);
推荐阅读
- beautifulsoup - 美丽的汤词表
- javascript - 尝试加载图像时写入 {% load static %} 时出现语法错误
- python - Python BeautifulSoup 在某些级别下无法找到标签
- sql - Docker 入口点 initdb 权限被拒绝
- python - pytesseract 和 opencv 读取文本的问题
- javascript - 我使用 Workbox CLI 及其 service-worker 生成器的 PWA 无法离线工作
- python - 预提交内置钩子的入口命令
- java - 带有 Viewholder 的 Android Recyclerview 更改宽度和高度 onClick
- javascript - 如何在 Next.js 中使用 stopPropagation()?
- parsing - 计算语法的 First 和 Follow