Bruce Bruce - 1 year ago 59
PHP Question

PHP directory and file information in an array

So there is user directory space. Each user gets their own space and they can upload .gif, jpg, png, and mp4 files to them.

The user can create and manage their own files in as many directories or sub-directories as they wish.

I have no idea how to do what I need to for my end result so I have no example code. What I need for an end result is as follows:

foreach ($file AS $file) {
$data[] = array('type' => 'image',
'path' => $file["path"],
'name' => $file[name],
'time' => $file["update_time"]);

How exactly would I get the details from the directories keeping in mind I have no idea what the structure will look like after the base directory.

Also, I need to exclude all directories and files that begin with a . (such as .htaccess, but there are others)

Answer Source

Here you go. Usa recursive function to iterate on each directory. If it is a directory do the recursion, otherwise get and store data:

$directoryToScan = './';
$results = [];
$tree = getDirEnties($directoryToScan, $results);

function getDirEnties($directory, &$results) {
    $entries = scandir($directory);
    foreach ($entries as $item) {
        if (!in_array($item, ['.', '..']) && substr($item, 0, 1) !== '.') {
            $path = $directory . '/' . $item;
            if (is_dir($path)) {
                getDirEnties($path, $results);
            } else {
                $pathInfo = pathinfo($path);
                $name = $pathInfo['filename'];
                $type = 'unknown';
                if (!empty($pathInfo['extension'])) {
                    $name .= "." . $pathInfo['extension'];
                    switch (strtolower($pathInfo['extension'])) {
                        case "gif":
                        case "jpg":
                        case "png":
                        case "jpeg":
                        case "bmp":
                            $type = 'image';
                        case "mp4":
                            $type = 'media';
                $data = [
                    'name' => $name,
                    'path' => $pathInfo['dirname'],
                    'type' => $type,
                    'time' => filemtime($path)
                $results[] = $data;
    return $results;