php - 如何修复共享主机上的 mkdir()“只读文件系统”?
问题描述
我正在尝试设置允许用户将文件上传到服务器上的目录(共享主机)的功能。用户可以输入上传文件夹名称并选择文件。如果该文件夹不存在,则会创建它。
请注意,这不是大型上传系统,但仅适用于一个用户。
我的代码在localhost
. 使用公共服务器(共享主机),可以创建文件夹。但其中没有文件显示。
上传功能,process.php
:
// run code only if post request went through
if ($_SERVER['REQUEST_METHOD'] === 'POST' ) {
if (isset($_POST['folder'])) {
$folder = $_POST['folder'];
} else {
$folder = 'new-folder';
}
// ensure that there are files inside the array to actually upload
if (isset($_FILES['files'])) {
$errors = [];
$path = '/dir/data/uploads/images/' . $folder . "/";
// if folder does not exist, create it
if (!file_exists($path)) {
mkdir($path, 0777, true);
} else {
//stuff
}
$all_files = count($_FILES['files']['tmp_name']);
for ($i = 0; $i < $all_files; $i++) {
$file_name = $_FILES['files']['name'][$i];
$file_tmp = $_FILES['files']['tmp_name'][$i];
$file_type = $_FILES['files']['type'][$i];
$file_size = $_FILES['files']['size'][$i];
$tmp = explode('.', $_FILES['files']['name'][$i]);
$file_ext = strtolower(end($tmp));
$file = $path . $file_name;
// here follow multiple verifications on the file name, type, size, etc...
// removed to keep code shorter
if (empty($errors)) {
move_uploaded_file($file_tmp, $file);
}
}
if ($errors) print_r($errors);
}
}
尝试和观察:
在网络选项卡中,我得到
status code 200
.服务器上目标文件夹的读写执行权限
images
(暂时,用于测试!)设置为777
,(rwxrwxrwx)
。我测试了不同的文件和不同的文件夹名称(新的和现有的),但我尝试上传的文件从未出现。
我注意到尽管
mkdir($path, 0777, true);
在我的代码中使用了创建文件夹,但服务器上的文件夹的权限设置为705
,(rwx---r-x)
。我从运行良好的版本对此代码所做的唯一更改
localhost
是我更改了$path
.
我收到的错误消息:
Warning: mkdir(): Read-only file system in /path/to/scripts/process/process.php on line 31
/folder/data/uploads/images/test/image.webp --
Warning: move_uploaded_file(/folder/data/uploads/images/test/image.webp): failed to open stream: No such file or directory in /path/to/scripts/process/process.php on line 75
因此:
Warning: move_uploaded_file(): Unable to move (...)
- 第 31 行是
mkdir($path, 0777, true);
- 第 75 行是
move_uploaded_file($file_tmp, $file);
针对这个问题,我找到了几个针对 Linux 文件系统的修复程序。但是在使用共享主机时我该怎么做呢?
这是我第一次尝试这个,非常感谢帮助。
解决方案
我搜索并尝试了更多。这有效:
$path = $_SERVER['DOCUMENT_ROOT'] . '/data/uploads/images/' . $folder . "/";
我现在可以将文件上传到此文件夹中。
谢谢您的帮助!我一定会研究您建议的内容(并调整访问权限),因为PHP
这仍然不是我的强项。:)
推荐阅读
- docker - 我无法在 Linux mint 中启动我的 docker
- c - 函数,它返回指向 C 中指向 int 的指针的指针
- mongodb - MongoDB对分页结果应用排序
- java - 在java中返回相同的公共IP地址
- jsf - Websphere:java.lang.IllegalStateException:没有为此应用程序配置工厂
- php - PHP中变量之间的换行符
- apache-spark - 如何在pyspark数据框中读取scylladb表
- c# - 从数据库加载时出错。用户未与受信任的 SQL Server 连接关联
- c# - 在“Web API 重定向 (URI)”中获取查询字符串参数
- c++ - 如何以编程方式从 PKCS7 中提取 CA、多个 CA 和公共证书/密钥?