Skip to content
PHP Logo

How can a user select a directory for file upload in PHP using a directory tree?

When allowing users to upload files in PHP, you can provide them with a directory tree interface to select the destination directory for the upload. This can be achieved by displaying a list of directories in a tree-like structure and allowing the user to navigate through the directories to choose the desired location.

php
<?php
function listDirectories($path) {
    $directories = glob($path . '/*', GLOB_ONLYDIR);
    
    foreach ($directories as $directory) {
        echo '<option value="' . $directory . '">' . basename($directory) . '</option>';
        listDirectories($directory);
    }
}

echo '<select name="upload_directory">';
echo '<option value="">Select Directory</option>';
listDirectories('path/to/root/directory');
echo '</select>';
?>