umang
umang

Reputation: 127

Get filenames from folder

I want to allow users to select a folder by clicking on upload button . On submit , I want to retrieve all filenames from folder (recursively) , without uploading any file or folder.

Example , Lets say there is folder name Test with following folder structure :
Test
- 1.txt
- 2.pdf
- 3.avi
- Test2 (Folder, contains multiple files)
- 4.mp4

On selecting Test folder on clicking upload button , output should be : 1.txt , 2.pdf , 3.avi, Test2 (filenames of file inside this folder) , 4.mp4

I don't need to get contents inside file , just the filename.

How should I do it ? I know there is chrome webkit directory which allows folder upload

<?php
$count = 0;
$name2 = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
foreach ($_FILES['files']['name'] as $i => $name) {
    if (strlen($_FILES['files']['name'][$i]) > 1) {
        $count++;

        array_push($name2, $_FILES['files']['name'][$i]);
    }
}
}
?>

<!DOCTYPE HTML>
<html>

<body>
  <form method="post" enctype="multipart/form-data">
    <input type="file" name="files[]" id="files" multiple="" directory="" webkitdirectory="" mozdirectory="">
    <input class="button" type="submit" value="Upload" />
  </form>
</body>

</html>

$name2 array return list of filenames
Above code does not work for video files and is not compatible with other browsers.

Is there any other way of doing it ?

Upvotes: 2

Views: 2523

Answers (1)

Osuwariboy
Osuwariboy

Reputation: 1375

PHP provides you with an object called the filesystemiterator that's designed to help you loop through a designated folder. In your case, I'd do a recursive function that would look like this:

function readFolder($folder)
{
    $retArray = array();
    $folder = new FilesystemIterator("path/to/folder", FilesystemIterator::SKIP_DOTS);
    foreach($folder as $file)
    {
        if(is_dir($file->getPathname())
            $retArray[] = readFolder($file->getPathname());
        else
            $retArray[] = $file->getFilename();
    }

    return $retArray;
}

What's nice about all this is that the getPathname() method returns the entire path of the file while if you just want the name of the file, you can just use the getFilename() method. Here's a link to the documentation on PHP's website:

http://php.net/manual/en/class.filesystemiterator.php

Also, for security purposes, modern web browsers do not include the full path to a file when you use the "file" input type.

Upvotes: 1

Related Questions