Search code examples
phpdrop-down-menuhtml-selectmkdir

Dropdown list with New folder option in PHP


I have this script that gets all the sub-directories and puts them into a dropdown list. I have an option "New folder" to create a new folder by gathering the folder name - in this case, it's numbers like 995 - and discount it by one to create a dir called 994

<form action="index.php" method="post">
<select name="folderchoose" id="folderchoose" onchange="this.form.submit();">
<?php
$base = basename("$items[1]", ".php").PHP_EOL;
$newbase = $base -1;
if($_POST['folderchoose']==0){ mkdir("../albums/$newbase", 0700); }
$items = glob("../albums/*", GLOB_ONLYDIR);
natsort($items);
{?><option>select:</option><?
    foreach($items as $item)
    {
         ?>  <option value="1"><? echo "$item\n "; ?></option><?
        } ?> <option value="0" >New folder</option> <? 
    }
?>
</select>
</form>
Directory:<?php echo $_POST[folderchoose]  ?><br />
<?php $base = basename("$items[1]", ".php").PHP_EOL;
$newbase = $base -1;
echo $newbase  ?>

Two things aren't working properly: the mkdir function doesn't get the $newbase and create a directory called dir(??) automatically even if I'm not choosing 'New Folder'.


Solution

  • I have a couple of hints for you to improve your code. I do not fully understand your problem but this might help.

    If you want to list a directory with all of its sub directories you should do something like this

    function list_directory( $dirname ) {
        foreach file in directory      
            if(is_dir($dirname)){
                list_directory($dirname)
            }
            if(is_File($dirname)){
                echo $dirname;
            }
        }
    }
    

    This is not usable code but a genral idea for you to work with.

    If strange things start happening try doing this

    var_dump( $var ); // The variable your are suspecting in your case $newbase