Sunday, January 3, 2010

Dynamically create multiple directories

I was looking for an easy way to dynamically create multiple directories with PHP, for example a directory and then sub-directories within the same script. Couldn't find anything so I came up with something on my own:

$first_directory = 'path/to/the/directory';
$second_directory = 'name-of-second-directory-relative-to-first';
mkdir($first_directory);
chdir($first_directory);
mkdir($second_directory);

What this does is create the first directory (path should be relative to the folder where the file calling your script resides), and move to that directory with chdir. Then the second directory is created within the first, path should be relative to the latter.

Of course there are many other applications. Enjoy!