PHP create nested directories

sunjie picture sunjie · Jul 5, 2011 · Viewed 24.3k times · Source

I need help with a function to create a 2 level directory for the following situations:

  1. The desired sub-directory exists in the parent directory, do nothing.
  2. Parent directory exists, sub-directory does not exist. Create only the sub-directory.
  3. Neither parent directory, nor the sub-directory exists, First create parent directory, then sub-directory.
  4. If Any of the directory was not created successfully, return FALSE.

Thanks for the help.

Answer

KingCrunch picture KingCrunch · Jul 5, 2011

Use the third parameter of mkdir():

recursive Allows the creation of nested directories specified in the pathname. Defaults to FALSE.

$path = '/path/to/folder/with/subdirectory';
mkdir($path, 0777, true);