Laravel fopen() 无法 create/read 文件

Laravel fopen() cant create/read file

所以我有这个 Laravel 项目,我想将一个数组导出到 json 文件以供以后使用。我对存储文件夹的权限是 777 但是当我这样做时

$line=[
  'key1'=>'value1',
];
file_put_contents("storage/app/test.json",json_encode($line));

我也试过了

$line=[
  'key1'=>'value1',
];
file_put_contents($_SERVER['DOCUMENT_ROOT']."/storage/app/test.json",json_encode($line));

在这两种情况下(加上更多)我都收到了这个错误

file_put_contents(storage/app/test.json): failed to open stream: No such file or directory

你知道为什么会这样吗?

编辑:文件夹存在

无论权限如何,您的目录都必须存在,然后才能尝试将文件放入其中。我认为这就是正在发生的事情。同样,您的权限可能设置在 storage 文件夹上,而不是 app 文件夹。

您正在使用 storage 文件夹,但默认情况下路径取自 public 这就是为什么您需要使用 ../
像这样尝试

$file=fopen('../storage/app/test.json','w');
fwrite($file,json_encode($line));
fclose($file);

您可以使用Laravel File Storage

您可以使用 Laravel 的辅助方法 base_path():

base_path 函数 returns 项目根目录的完全限定路径。

例如:

$fp = fopen(base_path() . 'app/Encryption/PrivateKeys/nginx-selfsigned.key','r');

您好,我遇到了一个更相似的问题。所以我在 storage/cpdpoints 中保存了一个文件,但我想读取该文件然后将其移动到 Public 文件夹

project/public/cdpoints.

我试过以下方法

    $file = Storage::path($path);
    $file = fopen($file, 'r');

    if ($file) {
          

            //get file original name
            $name = $file->getClientOriginalName();

            //create a unique file name using the time variable plus the name
            $file_name = time() . $name;

            //upload the file to a directory in Public folder
            $path = $file->move('cpdpoints', $file_name);
        }