Monday 3 September 2018

PHP: How to save a file in a directory that does not exist?

How can I save a file in a directory that does not exist?

In other words, it would have to automatically create the directory/sub-directories (if it does not exist) and then save the file to it.
Thanks.

Everyone provided an answer, but forgot to turn the recursive flag on. You must specify mkdir's third argument to true, to create directory tree (from mkdir manual):
<?php
// Desired folder structure
$structure = './depth1/depth2/depth3/';

// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.

if (!mkdir($structure, 0, true)) {
    die('Failed to create folders...');
}

// ...
?>

0 comments:

Post a Comment