Monday 24 September 2018

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 :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
    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.

0 comments:

Post a Comment