Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 543
sunjie Avatar asked Jul 05 '11 08:07

sunjie


People also ask

How to create a nested folder in PHP?

// Desired folder structure $structure = './depth1/depth2/depth3/'; // To create the nested structure, the $recursive parameter // to mkdir() must be specified. if (! mkdir($structure, 0744, true)) { die('Failed to create folders...'); } Returns TRUE on success or FALSE on failure.

How create directory if not exists in PHP?

Methods: file_exists(): It is an inbuilt function that is used to check whether a file or directory exists or not. is_dir(): It is also used to check whether a file or directory exists or not. mkdir() : This function creates a directory.

What is mkdir in PHP?

The mkdir() creates a new directory with the specified pathname. The path and mode are sent as parameters to the mkdir() function and it returns TRUE on success or FALSE on failure. The mode parameter in mkdir() function is ignored on Windows platforms.


1 Answers

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); 
like image 120
KingCrunch Avatar answered Sep 22 '22 14:09

KingCrunch