Laravel fopen() 无法创建/读取文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45353458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:23:15  来源:igfitidea点击:

Laravel fopen() cant create/read file

phpjsonlaravelfilefopen

提问by Dimitrios Stefos

so I have this Laravel project and I want to export an array to a json file to use it later. My permissions on the storage folder are 777 but when I do

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

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

I also tried

我也试过

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

and in both cases (plus some more) I get this error

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

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

Do you have any idea why is this happening?

你知道为什么会这样吗?

EDIT: The folders exist

编辑:文件夹存在

回答by Bibhudatta Sahoo

You are working with storagefolder but by default the path takes from publicthat why you need to use ../
Try like this

您正在使用存储文件夹,但默认情况下,路径来自公共,这就是为什么您需要使用这样的 ../
尝试

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

回答by Grey

You can use Laravel File Storage

您可以使用Laravel 文件存储

回答by user3785966

You can use Laravel's helper method base_path():

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

The base_path function returns the fully qualified path to the project root.

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

Eg:

例如:

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

回答by ebraley

Your directories have to exist before attempting to put files in them, regardless of permissions. I assume that's what is occurring. Likewise your permissions may be set on the storagefolder, but not the appfolder.

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