首页 > 解决方案 > 如何修复共享主机上的 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);
    } 
}

尝试和观察:

我收到的错误消息:

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 (...)

针对这个问题,我找到了几个针对 Linux 文件系统的修复程序。但是在使用共享主机时我该怎么做呢?

这是我第一次尝试这个,非常感谢帮助。

标签: phpfile-permissionsshared-hostingmkdir

解决方案


我搜索并尝试了更多。这有效:

 $path = $_SERVER['DOCUMENT_ROOT'] . '/data/uploads/images/' . $folder . "/";

我现在可以将文件上传到此文件夹中。

谢谢您的帮助!我一定会研究您建议的内容(并调整访问权限),因为PHP这仍然不是我的强项。:)


推荐阅读