oncode
12/17/2014 - 3:44 PM

Create a file in previously non existing folders.

Create a file in previously non existing folders.

<?php
// content of the new file
$data = 'Test file content.';

// path to new file
$dir = 'folder/non-existing-subfolder/non-existing-subfolder2/file.txt';

$parts = explode('/', $dir);
$file = array_pop($parts);
$dir = '';

// create non existing folders
foreach ($parts as $part) {
  if (!is_dir($dir .= $part . '/')) {
    mkdir($dir);
  }
}

file_put_contents($dir . $file, $data);