Jason
Jason

Reputation: 708

List files and subfolders from database in PHP

Beginner : I cant seem to get my head around the logic of it. Have searched but seems to come up with listing files and folders from an actual directory ie. (opendir).

My problem is :

Im trying to work out (in PHP) how to list files and subfolders from a path stored in a database. (Without any access to the file or dir, so just from the path name)

For example database shows:

main/home/television.jpg
main/home/sofa.jpg
main/home/bedroom/bed.jpg
main/home/bedroom/lamp.jpg

So if i specify main/home - it shows: television.jpg, sofa.jpg and the name of the subfolder : bedroom.

Upvotes: 0

Views: 333

Answers (2)

Steve Robbins
Steve Robbins

Reputation: 13802

scanFolder('main/home');

function scanFolder($dir) {

    foreach (scandir($dir) as $file) {

        if (!in_array($file, array('.', '..'))) {

            if (is_dir($file)) {

                scanFolder($dir . '/' . $file);
            }
            else {

                echo $dir . '/' . $file . "\n";
            }
        }
    }
}

Upvotes: 1

thescientist
thescientist

Reputation: 2948

You would probably want to check on each iteration if the filename is a directory or not. If it is, open it up and read its contents and output them. A recursive function would work best in this situation.

http://php.net/manual/en/function.is-dir.php

Upvotes: 0

Related Questions