【问题标题】:Creating a folder when I run file_put_contents()运行 file_put_contents() 时创建文件夹
【发布时间】:2012-11-02 13:22:01
【问题描述】:

我从网站上传了很多图片,需要以更好的方式组织文件。 因此,我决定按月创建一个文件夹。

$month  = date('Yd')
file_put_contents("upload/promotions/".$month."/".$image, $contents_data);

我试过这个后,我得到错误结果。

消息:file_put_contents(upload/promotions/201211/ang232.png):打开流失败:没有这样的文件或目录

如果我试图只将文件放在现有文件夹中,它会起作用。但是,它无法创建新文件夹。

有没有办法解决这个问题?

【问题讨论】:

    标签: php


    【解决方案1】:

    我从@Manojkiran.A 和@Savageman 创建了一个更简单的答案。此函数可用作 file_put_contents 的直接替换。它不支持上下文参数,但我认为对于大多数情况应该足够了。我希望这可以帮助一些人。快乐编码! :)

    function force_file_put_contents (string $pathWithFileName, mixed $data, int $flags = 0) {
      $dirPathOnly = dirname($pathWithFileName);
      if (!file_exists($directoryPathOnly)) {
        mkdir($dirPathOnly, 0775, true); // folder permission 0775
      }
      file_put_contents($pathWithFileName, $data, $flags);
    }
    

    【讨论】:

      【解决方案2】:

      我一直在使用 Crud Generator 进行 laravel 项目,但这个方法不起作用

      @aqm 所以我创建了自己的函数

      PHP方式

      function forceFilePutContents (string $fullPathWithFileName, string $fileContents)
          {
              $exploded = explode(DIRECTORY_SEPARATOR,$fullPathWithFileName);
      
              array_pop($exploded);
      
              $directoryPathOnly = implode(DIRECTORY_SEPARATOR,$exploded);
      
              if (!file_exists($directoryPathOnly)) 
              {
                  mkdir($directoryPathOnly,0775,true);
              }
              file_put_contents($fullPathWithFileName, $fileContents);    
          }
      

      LARAVEL 方式

      不要忘记在文件顶部添加

      use Illuminate\Support\Facades\File;

      function forceFilePutContents (string $fullPathWithFileName, string $fileContents)
          {
              $exploded = explode(DIRECTORY_SEPARATOR,$fullPathWithFileName);
      
              array_pop($exploded);
      
              $directoryPathOnly = implode(DIRECTORY_SEPARATOR,$exploded);
      
              if (!File::exists($directoryPathOnly)) 
              {
                  File::makeDirectory($directoryPathOnly,0775,true,false);
              }
              File::put($fullPathWithFileName,$fileContents);
          }
      

      【讨论】:

      • $directoryPathOnly = dirname($fullPathWithFileName) ;)
      【解决方案3】:

      file_put_contents() 不创建目录结构。只有文件。

      您需要在脚本中添加逻辑以测试 month 目录是否存在。如果没有,请先使用mkdir()

      if (!is_dir('upload/promotions/' . $month)) {
        // dir doesn't exist, make it
        mkdir('upload/promotions/' . $month);
      }
      
      file_put_contents('upload/promotions/' . $month . '/' . $image, $contents_data);
      

      更新:mkdir() 接受$recursive 的第三个参数,这将创建任何 缺失的目录结构。如果您需要创建多个目录,可能会很有用。

      递归和目录权限设置为 777 的示例:

      mkdir('upload/promotions/' . $month, 0777, true);
      

      【讨论】:

      【解决方案4】:

      修改上述答案使其更通用,(自动检测并从系统斜杠上的任意文件名创建文件夹)

      ps 之前的回答太棒了

      /**
       * create file with content, and create folder structure if doesn't exist 
       * @param String $filepath
       * @param String $message
       */
      function forceFilePutContents ($filepath, $message){
          try {
              $isInFolder = preg_match("/^(.*)\/([^\/]+)$/", $filepath, $filepathMatches);
              if($isInFolder) {
                  $folderName = $filepathMatches[1];
                  $fileName = $filepathMatches[2];
                  if (!is_dir($folderName)) {
                      mkdir($folderName, 0777, true);
                  }
              }
              file_put_contents($filepath, $message);
          } catch (Exception $e) {
              echo "ERR: error writing '$message' to '$filepath', ". $e->getMessage();
          }
      }
      

      【讨论】:

      • 绝对没必要...您可以检查目录是否存在。如果不打电话给mkdir($fileDestinationDir, 0777, true);。然后拨打file_put_contents。虽然 *NIX 系统使用 / 作为目录分隔符,但 Windows 不在乎,您可以使用 mkdir('/path/with/forward/slashes') 没有任何问题。
      【解决方案5】:

      我写了一个你可能喜欢的函数。它被称为 forceDir()。它基本上检查您想要的目录是否存在。如果是这样,它什么也不做。如果没有,它将创建目录。使用这个函数而不只是 mkdir 的一个原因是这个函数也可以创建下一个文件夹。例如('upload/promotions/januari/firstHalfOfTheMonth')。只需将路径添加到所需的 dir_path。

      function forceDir($dir){
          if(!is_dir($dir)){
              $dir_p = explode('/',$dir);
              for($a = 1 ; $a <= count($dir_p) ; $a++){
                  @mkdir(implode('/',array_slice($dir_p,0,$a)));  
              }
          }
      }
      

      【讨论】:

      • 你也可以将true作为第三个参数添加到mkdir()中。
      猜你喜欢
      • 2013-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2015-10-24
      • 1970-01-01
      相关资源
      最近更新 更多