PHP create nested directories for a given path

By | October 22, 2011

If a file is to be saved in at path /var/www/a/b/c/d/abc.zip where the directory c and d dont exist then the directories have to created.

Here is a function that uses recursion to check for directories in a path and create them if they do not exist :

/**
	Make a nested path , creating directories down the path
	Recursion !!
*/
function make_path($path)
{
	$dir = pathinfo($path , PATHINFO_DIRNAME);
	
	if( is_dir($dir) )
	{
		return true;
	}
	else
	{
		if( make_path($dir) )
		{
			if( mkdir($dir) )
			{
				chmod($dir , 0777);
				return true;
			}
		}
	}
	
	return false;
}

make_path('/var/www/a/b/c/d/abc.zip');

The above will create the directories a b c and d , after that the path can be used to save a file or do something similar.

About Silver Moon

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected].

Leave a Reply

Your email address will not be published. Required fields are marked *