2
mkdir ("dir1/{dir1-1,dir1-2}",0755,TRUE);

This command creates the folder dir1 with a single subfolder called '{dir1-1,dir1-2}' instead of creating dir1-1 and dir1-2 as two subfolders for dir1.

Any idea how to get this to work from a single mkdir command as above?

8
  • 4
    Simple: You can't. What makes you think you can? And why not just call mkdir() twice? Commented Apr 27, 2012 at 23:16
  • @DaveRandom This is what makes me think I can: developmentality.wordpress.com/2010/04/11/… Except it's not working for me from that example, but it seems possible. Also, say you have 10 subdirectories, it's much more efficient and cleaner doing it in one mkdir command Commented Apr 27, 2012 at 23:20
  • 1
    @MikePurcell The TRUE there makes it recursive I believe Commented Apr 27, 2012 at 23:20
  • 1
    @Maverick Those are arguments being passed to the unix mkdir command, not the PHP function. The PHP functions using OS calls, it does not execute mkdir. If you want to implement functionality like this, you will have to write it yourself I'm afraid... PHP's mkdir() takes one literal path and attempts to create it, it performs no parsing of the string you passed. Commented Apr 27, 2012 at 23:22
  • 1
    It's bash doing the expansion in that article. You'd have to emulate the same thing in PHP, effectively calling mkdir multiple times. Commented Apr 27, 2012 at 23:23

2 Answers 2

6

PHP does not support brace expansion in the same way as the shell does. If you want to create multiple directories, you will have to call mkdir() multiple times, and you can easily do this by looping.

You can pass TRUE as the third argument to mkdir() - this means that all directories back up the tree will also be created if they do not exist and the parent is writable. You can safely pass TRUE to all calls when operating in a loop, the first iteration for a given directory will create it, subsequent calls will have no adverse effect.

For example:

$toCreate = array(
  'dir1/dir1-1',
  'dir1/dir1-2'
);

$permissions = 0755;

foreach ($toCreate as $dir) {
  mkdir($dir, $permissions, TRUE);
}
Sign up to request clarification or add additional context in comments.

Comments

1

shell mkdir can do:

mkdir -p /foo/bar/peng

so now you might just call the external shell command from within php. But be careful about security.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.