Home > Enterprise >  How can i create a folder and subfolder in PHP using a variable?
How can i create a folder and subfolder in PHP using a variable?

Time:10-15

I have to create a root folder that uses the $username variable (coming from a previous section of the script), and then, inside this root folder, I need to create the /JS, /PHP and the /CSS subfolders.

I have tried the following (just for the JS subfolder) but it does not work. I receive no error but the JS subfolder is not created (the root folder is created):

$rootpath = $username. '/';
$jspath = $rootpath. '/js/';
return is_dir($rootpath) || mkdir($rootpath, 0777, true);
return is_dir($jspath) || mkdir($jspath);

What am i doing wrong? Thank you in advance. Kindest regards,

CodePudding user response:

I try to explain your code:

is_dir($rootpath) return true if the $rootpath exist, then mkdir($rootpath, 0777, true); do not get executed.

If $rootpath does not exist, then mkdir($rootpath, 0777, true); is executed

So at this point you have $rootpath folder and the code exit (or better return) due to the return in front of the commands

Your code should be as follow:

$rootpath = $username. '/';
$subfolders=[
    'js',
    'css',
    'php',
];
foreach ($subfolders as $folder) {
    $path = $rootpath . $folder;
    if (!mkdir($path, 0777, true) || !is_dir($path)) {
        // you can either return false or an exception, it is up to you
        return false;
        // throw new \RuntimeException("Directory '$path' was not created');
    }
}
return true; 

CodePudding user response:

@roberto-braga has explained your code very well. There is another solution i like to give you. If you sure that certain directories is not exist and directly you want to create. You can use this piece of code.

    $structure = './'.$username.'/depth1/depth2/depth3/';

    if (!mkdir($structure, 0777, true)) {
       die('Failed to create directories...');
    }

I like to give you another suggestion that before try the code make sure you have proper permission to create , edit and delete folder.

CodePudding user response:

I will advise you to use a function

// list os subdirectories to be made
$subdirectoryarrays = [
    'js','css','php'
];
function makeCustomDir($directory_name,$subdirectoryarrays){
    $rootpath = $directory_name. '/';
    is_dir($rootpath) || mkdir($rootpath, 0755, true);
    foreach ($subdirectoryarray as $newroot) {
        $tobecreated = $rootpath. '/'.$newroot.'/';
        is_dir($tobecreated) || mkdir($tobecreated);
    }
    return true;
}
makeCustomDir('name_of_folder',$subdirectoryarrays);
  • Related