PHP create nested directories for a given path

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.







Last Updated On : 22nd October 2011

Subscribe to get updates delivered to your inbox

Leave a comment