sunjie sunjie - 4 months ago 82
PHP Question

PHP create nested directories

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

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);