【问题标题】:Laravel fopen() cant create/read fileLaravel fopen()无法创建/读取文件
【发布时间】:2018-01-03 08:10:44
【问题描述】:

所以我有这个 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吗?
  • 当然,我也有文件,但是如果文件不存在,我希望它自动创建文件

标签: php json laravel file fopen


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 有效!它在路径之前需要这两个点,我认为这是因为它需要从“公共”文件夹中上升。谢谢!!!!
    • 欢迎您,因为您的问题已解决,请接受我的回答并给我一个大拇指:)
    • 当然! Stackoverflow 不让我这样做,我不得不等待几分钟
    • @DimitriosStefos 既然您使用的是 Laravel,那么您不妨尽可能使用 Storage 门面。可以在here 找到文档。它只是一个包装器,但您可能不会遇到这种情况。
    【解决方案3】:

    您可以使用Laravel File Storage

    【讨论】:

    • 太棒了!快速简单!谢谢@
    【解决方案4】:

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

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

    例如:

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

    【讨论】:

      【解决方案5】:

      嗨,团队,我面临着更类似的问题。所以我在 storage/cpdpoints 中保存了一个文件,但我想读取该文件然后将其移动到 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);
              }
      

      【讨论】:

        猜你喜欢
        • 2014-06-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-22
        • 2013-10-04
        • 2015-10-26
        • 1970-01-01
        相关资源
        最近更新 更多